Here are the examples of the java api org.apache.http.client.methods.HttpPost taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2174 Examples
19
Source : HttpClient.java
with Apache License 2.0
from ZTO-Express
with Apache License 2.0
from ZTO-Express
/**
* post请求
*
* @param url
* @param jsonStr
* @param connectTimeout
* @param socketTimeout
* @return
* @throws IOException
*/
public static String post(String url, String jsonStr, int connectTimeout, int socketTimeout) throws IOException {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json; charset=" + CHAR_SET);
RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
httpPost.setConfig(config);
StringEnreplacedy se = new StringEnreplacedy(jsonStr, CHAR_SET);
httpPost.setEnreplacedy(se);
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EnreplacedyUtils.toString(response.getEnreplacedy(), CHAR_SET);
}
} finally {
if (null != response) {
IOUtils.close(response.getEnreplacedy().getContent());
}
}
logger.warn("request is failure,url:{},body:{},statusCode:{}", url, jsonStr, response.getStatusLine().getStatusCode());
throw new RuntimeException("request is failure,code:" + response.getStatusLine().getStatusCode());
}
19
Source : NotificationService.java
with Apache License 2.0
from ZTO-Express
with Apache License 2.0
from ZTO-Express
public void sendDingdingGroup(AlertRuleConfig rule) {
HttpPost httppost = new HttpPost(rule.getAlertDingding());
httppost.addHeader("Content-Type", "application/json; charset=utf-8");
Map<String, Object> map = new HashMap<>();
map.put("msgtype", "text");
Map<String, Object> content = new HashMap<>();
content.put("content", rule.getDescription());
map.put("text", content);
String errorMsg = JSON.toJSONString(map);
StringEnreplacedy se = new StringEnreplacedy(errorMsg, "utf-8");
httppost.setEnreplacedy(se);
HttpResponse response = null;
try {
response = httpClient.execute(httppost);
logger.info("send {} dingding group msg:{} ", rule.getRuleKey(), response.getStatusLine().getStatusCode());
} catch (IOException e) {
logger.error("send {} dingding group failed", rule.getRuleKey(), e);
} finally {
try {
if (null != response) {
IOUtils.closeQuietly(response.getEnreplacedy().getContent());
}
} catch (IOException e) {
logger.error("close error", e);
}
}
}
19
Source : HttpUtils.java
with MIT License
from Zo3i
with MIT License
from Zo3i
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEnreplacedy formEnreplacedy = new UrlEncodedFormEnreplacedy(nameValuePairList, "utf-8");
formEnreplacedy.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEnreplacedy(formEnreplacedy);
}
return httpClient.execute(request);
}
19
Source : HttpUtils.java
with MIT License
from Zo3i
with MIT License
from Zo3i
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEnreplacedy(new ByteArrayEnreplacedy(body));
}
return httpClient.execute(request);
}
19
Source : HttpUtils.java
with MIT License
from Zo3i
with MIT License
from Zo3i
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEnreplacedy(new StringEnreplacedy(body, "utf-8"));
}
return httpClient.execute(request);
}
19
Source : HttpClientUtils.java
with MIT License
from Zo3i
with MIT License
from Zo3i
/**
* http的post请求,传递map格式参数
*/
public static String post(String url, Map<String, String> dataMap, String charset) {
HttpPost httpPost = new HttpPost(url);
try {
if (dataMap != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : dataMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEnreplacedy formEnreplacedy = new UrlEncodedFormEnreplacedy(nvps, charset);
formEnreplacedy.setContentEncoding(charset);
httpPost.setEnreplacedy(formEnreplacedy);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return executeRequest(httpPost, charset);
}
19
Source : HttpClientUtils.java
with MIT License
from Zo3i
with MIT License
from Zo3i
/**
* http的post请求,增加异步请求头参数,传递json格式参数
*/
public static String ajaxPostJson(String url, String jsonString, String charset) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
// try {
// 解决中文乱码问题
StringEnreplacedy stringEnreplacedy = new StringEnreplacedy(jsonString, charset);
stringEnreplacedy.setContentEncoding(charset);
stringEnreplacedy.setContentType("application/json");
httpPost.setEnreplacedy(stringEnreplacedy);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
return executeRequest(httpPost, charset);
}
19
Source : HttpClientUtils.java
with MIT License
from Zo3i
with MIT License
from Zo3i
/**
* http的post请求,增加异步请求头参数,传递map格式参数
*/
public static String ajaxPost(String url, Map<String, String> dataMap, String charset) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
try {
if (dataMap != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : dataMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEnreplacedy formEnreplacedy = new UrlEncodedFormEnreplacedy(nvps, charset);
formEnreplacedy.setContentEncoding(charset);
httpPost.setEnreplacedy(formEnreplacedy);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return executeRequest(httpPost, charset);
}
19
Source : HttpUtils.java
with Apache License 2.0
from zhuangjinming16
with Apache License 2.0
from zhuangjinming16
/**
* Post stream
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
}
if (body != null) {
request.setEnreplacedy(new ByteArrayEnreplacedy(body));
}
return httpClient.execute(request);
}
19
Source : HttpUtils.java
with Apache License 2.0
from zhuangjinming16
with Apache License 2.0
from zhuangjinming16
/**
* post form
*
* @param host
* @param path
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEnreplacedy formEnreplacedy = new UrlEncodedFormEnreplacedy(nameValuePairList, "utf-8");
formEnreplacedy.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEnreplacedy(formEnreplacedy);
}
return httpClient.execute(request);
}
19
Source : HttpUtils.java
with Apache License 2.0
from zhuangjinming16
with Apache License 2.0
from zhuangjinming16
/**
* Post String
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, Map<String, String> headers, Map<String, String> querys, String body) throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
}
if (StringUtils.isNotBlank(body)) {
request.setEnreplacedy(new StringEnreplacedy(body, "utf-8"));
}
return httpClient.execute(request);
}
19
Source : ServerRequester.java
with Apache License 2.0
from zhongxunking
with Apache License 2.0
from zhongxunking
// 构建请求
private HttpUriRequest buildRequest(String iderId, int amount) {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("iderId", iderId));
params.add(new BasicNameValuePair("amount", Integer.toString(amount)));
HttpPost httpPost = new HttpPost(acquireIdsUrl);
httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(params, Charset.forName("utf-8")));
return httpPost;
}
19
Source : HttpUtils.java
with Apache License 2.0
from zhangdaiscott
with Apache License 2.0
from zhangdaiscott
/**
* post提交json数据
* @param url
* @param jsonStr
* @return
*/
public static String doPostJson(String url, String jsonStr) {
String result = null;
HttpPost post = new HttpPost(url);
try {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
post.setConfig(requestConfig);
post.addHeader("content-type", "application/json");
StringEnreplacedy myEnreplacedy = new StringEnreplacedy(jsonStr, "UTF-8");
post.setEnreplacedy(myEnreplacedy);
HttpResponse response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
if (resEnreplacedy != null) {
// String respBody = new String(EnreplacedyUtils.toString(resEnreplacedy).getBytes("ISO_8859_1"),"GBK");
// String respBody = new String(EnreplacedyUtils.toString(resEnreplacedy,"UTF-8"));
String respBody = new String(EnreplacedyUtils.toString(resEnreplacedy));
try {
result = respBody;
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
post.releaseConnection();
}
return result;
}
19
Source : HttpUtils.java
with Apache License 2.0
from zhangdaiscott
with Apache License 2.0
from zhangdaiscott
/**
* post方式提交表单(模拟用户登录请求)
*/
// BasicNameValuePair
public static String postForm(String url, List<NameValuePair> formparams) {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
httppost.setConfig(requestConfig);
// 创建参数队列
// List<NameValuePair> formparams = new ArrayList<NameValuePair>();
// formparams.add(new BasicNameValuePair("username", "admin"));
// formparams.add(new BasicNameValuePair("preplacedword", "123456"));
UrlEncodedFormEnreplacedy uefEnreplacedy;
try {
uefEnreplacedy = new UrlEncodedFormEnreplacedy(formparams, "UTF-8");
httppost.setEnreplacedy(uefEnreplacedy);
log.debug("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
if (enreplacedy != null) {
String result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
log.debug("--------------------------------------");
log.debug("Response content: " + result);
log.debug("--------------------------------------");
return result;
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
19
Source : HttpUtils.java
with Apache License 2.0
from zhangdaiscott
with Apache License 2.0
from zhangdaiscott
/**
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
* @return
*/
public static String post(String url, HashMap<String, String> map) {
String result = "";
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
httppost.setConfig(requestConfig);
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
formparams.add(new BasicNameValuePair(key.toString(), map.get(key)));
}
UrlEncodedFormEnreplacedy uefEnreplacedy;
try {
uefEnreplacedy = new UrlEncodedFormEnreplacedy(formparams, "UTF-8");
httppost.setEnreplacedy(uefEnreplacedy);
// System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
if (enreplacedy != null) {
// System.out.println("--------------------------------------");
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
log.info("Response content: " + result);
// System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
19
Source : locapiCellidClientUtil.java
with Apache License 2.0
from zengfr
with Apache License 2.0
from zengfr
protected static String parse(String lac, String cId, String flag, String charest) throws IOException {
String urlString = String.format(api, lac, cId, flag);
HttpPost post = new HttpPost(urlString);
post.setHeader("Referer", homePage);
post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0");
HttpResponse resp = client.execute(post);
return getContent(resp, charest);
}
19
Source : locapiBaiduClientUtil.java
with Apache License 2.0
from zengfr
with Apache License 2.0
from zengfr
protected static locapiRespBody parse(locapiReq req) throws IOException {
StringBuffer sb = new StringBuffer();
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(api);
String reqStr = JSON.toJSONString(req);
StringEnreplacedy se = new StringEnreplacedy(reqStr);
System.out.println(reqStr);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
HttpEnreplacedy enreplacedy = resp.getEnreplacedy();
BufferedReader br = new BufferedReader(new InputStreamReader(enreplacedy.getContent()));
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
// 740 Failed to authenticate for api loc is forbidden.(服务被禁用,一般不会出现)
System.out.println(sb);
return JSON.parseObject(sb.toString(), locapiRespBody.clreplaced);
}
19
Source : Log.java
with Apache License 2.0
from zekroTJA
with Apache License 2.0
from zekroTJA
/**
* Method by StupPlayer (https://github.com/StupPlayer)
* @param data
* @return
*/
public static String hastePost(String data) {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("https://hastebin.com/doreplacedents");
try {
post.setEnreplacedy(new StringEnreplacedy(data));
HttpResponse response = client.execute(post);
String result = EnreplacedyUtils.toString(response.getEnreplacedy());
return "https://hastebin.com/" + new JsonParser().parse(result).getAsJsonObject().get("key").getreplacedtring();
} catch (IOException e) {
e.printStackTrace();
}
return "Could not post!";
}
19
Source : GitHubClient.java
with Apache License 2.0
from zebrunner
with Apache License 2.0
from zebrunner
@SneakyThrows
public String getAccessToken(String code) {
URIBuilder uriBuilder = new URIBuilder(String.format(GITHUB_ACCESS_TOKEN_PATH, gitHubHost));
uriBuilder.addParameter("client_id", gitHubClientId).addParameter("client_secret", gitHubSecret).addParameter("code", code).addParameter("accept", "json");
HttpPost getAccessTokenRequest = new HttpPost(uriBuilder.build());
getAccessTokenRequest.addHeader("Accept", "application/json");
HttpResponse httpResponse = httpClient.execute(getAccessTokenRequest);
String response = EnreplacedyUtils.toString(httpResponse.getEnreplacedy());
return parseValue(response, "access_token");
}
19
Source : WXPay.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
@SuppressWarnings("rawtypes")
@Override
public <T> Object refund(T t) throws Exception {
WXRefundParams wxRefundParams = (WXRefundParams) t;
String path = this.getClreplaced().getResource("/apiclient_cert.p12").getPath();
HttpClient client = HttpUtil.createSSL(path, WXPayUtil.MCHID);
Map<String, String> params = new HashMap<>();
params.put("appid", wxRefundParams.getAppId());
params.put("mch_id", wxRefundParams.getMchId());
params.put("nonce_str", wxRefundParams.genNonceStr());
params.put("out_trade_no", wxRefundParams.getOutTradeNo());
params.put("out_refund_no", wxRefundParams.getOutRefundNo());
params.put("total_fee", String.valueOf((int) (wxRefundParams.getTotalFee() * 100)));
params.put("refund_fee", String.valueOf((int) (wxRefundParams.getRefundFee() * 100)));
params.put("op_user_id", "1446023502");
String sign = WXPayUtil.getSign(params);
params.put("sign", sign);
String xmlstring = XMLUtil.toXml(params);
HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(xmlstring, "utf-8");
post.setEnreplacedy(postEnreplacedy);
String result = null;
HttpResponse response = client.execute(post);
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
Map map = XMLUtil.getMapFromXML(result);
return map;
}
19
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
public static String sendJSONPost(String url, String jsonData, Map<String, String> headers) {
String result = null;
HttpPost httpPost = new HttpPost(url);
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(jsonData, CHARSET_NAME);
postEnreplacedy.setContentType("application/json");
httpPost.setEnreplacedy(postEnreplacedy);
httpPost.setHeader("Content-Type", "application/json");
HttpClient client = HttpClients.createDefault();
if (headers != null && !headers.isEmpty()) {
headers.forEach((k, v) -> {
httpPost.setHeader(k, v);
});
}
try {
HttpResponse response = client.execute(httpPost);
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
} catch (Exception e) {
logger.error("http request error ", e);
} finally {
httpPost.abort();
}
return result;
}
19
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
public static String sendPost(String url, String cnt) {
String result = null;
HttpPost httpPost = new HttpPost(url);
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(cnt, CHARSET_NAME);
httpPost.setEnreplacedy(postEnreplacedy);
httpPost.addHeader("Content-Type", "text/xml");
HttpClient client = HttpClients.createDefault();
try {
HttpResponse response = client.execute(httpPost);
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
} catch (ConnectionPoolTimeoutException e) {
logger.error("message get throw ConnectionPoolTimeoutException(wait time out)");
} catch (ConnectTimeoutException e) {
logger.error("message get throw ConnectTimeoutException");
} catch (SocketTimeoutException e) {
logger.error("message get throw SocketTimeoutException");
} catch (Exception e) {
logger.error("message get throw Exception");
} finally {
httpPost.abort();
}
return result;
}
19
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
public static String sendPost(String url, String cnt, Map<String, String> headers) {
String result = null;
HttpPost httpPost = new HttpPost(url);
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(cnt, CHARSET_NAME);
httpPost.setEnreplacedy(postEnreplacedy);
httpPost.setHeader("Content-Type", "text/xml");
HttpClient client = HttpClients.createDefault();
if (headers != null && !headers.isEmpty()) {
headers.forEach((k, v) -> {
httpPost.setHeader(k, v);
});
}
try {
HttpResponse response = client.execute(httpPost);
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
} catch (Exception e) {
logger.error("http request fail", e);
} finally {
httpPost.abort();
}
return result;
}
19
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
public static String postRequest(String url, List<NameValuePair> params) {
try {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
if (params != null) {
post.setEnreplacedy(new UrlEncodedFormEnreplacedy(params, CHARSET_NAME));
}
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEnreplacedy().getContent()));
StringBuilder res = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null) {
res.append(line);
}
return res.toString();
} catch (Exception e) {
logger.error("message req error=" + url, e);
return null;
}
}
19
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
/**
* 表单提交post请求
*
* @param url
* @param params
* @return
*/
public static String sendPostForm(String url, List<NameValuePair> params) {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
try {
UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(params, "UTF-8");
post.setEnreplacedy(enreplacedy);
HttpResponse response = client.execute(post);
String responseEnreplacedy = EnreplacedyUtils.toString(response.getEnreplacedy());
return responseEnreplacedy;
} catch (Exception e) {
logger.error("http请求失败 ----", e);
}
return null;
}
19
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
/**
* 表单提交post请求
*
* @param url
* @param params
* @return
*/
public static String sendPostForm(String url, List<NameValuePair> params, Map<String, String> headers) {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
if (headers != null && !headers.isEmpty()) {
headers.forEach((k, v) -> {
post.addHeader(k, v);
});
}
try {
UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(params, "UTF-8");
post.setEnreplacedy(enreplacedy);
HttpResponse response = client.execute(post);
String responseEnreplacedy = EnreplacedyUtils.toString(response.getEnreplacedy());
return responseEnreplacedy;
} catch (Exception e) {
logger.error("http请求失败 ----", e);
}
return null;
}
19
Source : HttpClientConnection.java
with Apache License 2.0
from yunhaibin
with Apache License 2.0
from yunhaibin
/**
* HttpClientConnection
*
* @author william.liangf
*/
public clreplaced HttpClientConnection implements HessianConnection {
private final HttpClient httpClient;
private final ByteArrayOutputStream output;
private final HttpPost request;
private volatile HttpResponse response;
public HttpClientConnection(HttpClient httpClient, URL url) {
this.httpClient = httpClient;
this.output = new ByteArrayOutputStream();
this.request = new HttpPost(url.toString());
}
public void addHeader(String key, String value) {
request.addHeader(new BasicHeader(key, value));
}
public OutputStream getOutputStream() throws IOException {
return output;
}
public void sendRequest() throws IOException {
request.setEnreplacedy(new ByteArrayEnreplacedy(output.toByteArray()));
this.response = httpClient.execute(request);
}
public int getStatusCode() {
return response == null || response.getStatusLine() == null ? 0 : response.getStatusLine().getStatusCode();
}
public String getStatusMessage() {
return response == null || response.getStatusLine() == null ? null : response.getStatusLine().getReasonPhrase();
}
public InputStream getInputStream() throws IOException {
return response == null || response.getEnreplacedy() == null ? null : response.getEnreplacedy().getContent();
}
public void close() throws IOException {
HttpPost request = this.request;
if (request != null) {
request.abort();
}
}
public void destroy() throws IOException {
}
}
19
Source : HttpClientConnection.java
with Apache License 2.0
from yunhaibin
with Apache License 2.0
from yunhaibin
public void close() throws IOException {
HttpPost request = this.request;
if (request != null) {
request.abort();
}
}
19
Source : WeChatUtil.java
with MIT License
from yunchaoyun
with MIT License
from yunchaoyun
/**
* 请求,只请求一次,不做重试
* @param domain
* @param urlSuffix
* @param uuid
* @param data
* @param connectTimeoutMs
* @param readTimeoutMs
* @param useCert 是否使用证书,针对退款、撤销等操作
* @return
* @throws Exception
*/
private static String httpRequest(String url, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert) throws Exception {
BasicHttpClientConnectionManager connManager;
if (useCert) {
// 证书
char[] preplacedword = weixinPayProperties.getMchId().toCharArray();
ClreplacedPathResource clreplacedPathResource = new ClreplacedPathResource("test.txt");
InputStream certStream = clreplacedPathResource.getInputStream();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(certStream, preplacedword);
// 实例化密钥库 & 初始化密钥工厂
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, preplacedword);
// 创建 SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, new DefaultHostnameVerifier());
connManager = new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslConnectionSocketFactory).build(), null, null, null);
} else {
connManager = new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build(), null, null, null);
}
HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
httpPost.setConfig(requestConfig);
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(data, "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.addHeader("User-Agent", USER_AGENT + " " + weixinPayProperties.getMchId());
httpPost.setEnreplacedy(postEnreplacedy);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEnreplacedy httpEnreplacedy = httpResponse.getEnreplacedy();
return EnreplacedyUtils.toString(httpEnreplacedy, "UTF-8");
}
19
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void db_insert_query() throws IOException {
String charset = "UTF-8";
HttpClient client = HttpClientBuilder.create().build();
String act = "addAndGet";
HttpPost post = new HttpPost(getUrl(act));
List<DemoUser> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
DemoUser obj = new DemoUser();
obj.setAge(r.nextInt(100));
obj.setName("名字" + r.nextInt());
obj.setId(r.nextLong());
list.add(obj);
}
Map<String, Object> json = new HashMap<>();
json.put("users", list);
StringEnreplacedy se = new StringEnreplacedy(S.json().toJson(json), charset);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
String line = resp.getStatusLine().toString();
System.out.println(line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String ret = EnreplacedyUtils.toString(resEnreplacedy, charset);
Log.get("db_insert_query").info("返回结果:" + ret);
System.out.println(ret);
}
19
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
// 测试需要登录的情况
@Test
public void login_sign() throws Exception {
String charset = "UTF-8";
HttpClient client = HttpClientBuilder.create().build();
login(client);
String act = "plain_sign";
Map<String, Object> json = new HashMap<>();
json.put("name", "小明");
String req = S.json().toJson(json);
String sign = Encrypt.sign(req.getBytes(charset));
HttpPost post = new HttpPost(getUrl(act) + "?sign=" + sign);
StringEnreplacedy se = new StringEnreplacedy(req, charset);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
// 以下验证请求是否正确
String line = resp.getStatusLine().toString();
replacedert.replacedertEquals("HTTP/1.1 200 OK", line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String ret = EnreplacedyUtils.toString(resEnreplacedy, charset);
replacedert.replacedertEquals("hello 小明,来自admin的问候", ret);
}
19
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void upload() throws IOException {
String charset = "UTF-8";
HttpClient client = HttpClientBuilder.create().build();
String act = "upload";
HttpPost post = new HttpPost(getUploadUrl(act));
Map<String, Object> json = new HashMap<>();
json.put("name", "张三");
json.put("age", 23);
String req = Base64.getEncoder().encodeToString(S.json().toJson(json).getBytes(charset));
System.out.println("req:" + req);
MultipartEnreplacedy reqEnreplacedy = new MultipartEnreplacedy();
reqEnreplacedy.addPart("Api", StringBody.create("common", "text/plain", Charset.forName(charset)));
reqEnreplacedy.addPart("param", StringBody.create(req, "text/plain", Charset.forName(charset)));
reqEnreplacedy.addPart("img", new FileBody(new File("logo_bluce.jpg")));
post.setEnreplacedy(reqEnreplacedy);
HttpResponse resp = client.execute(post);
String line = resp.getStatusLine().toString();
replacedert.replacedertEquals("HTTP/1.1 200 OK", line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
Log.get("upload").info(EnreplacedyUtils.toString(resEnreplacedy, charset));
}
19
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void base64() throws IOException {
String charset = "UTF-8";
HttpClient client = HttpClientBuilder.create().build();
String act = "base64";
HttpPost post = new HttpPost(getUrl(act));
Map<String, Object> json = new HashMap<>();
json.put("echo", "你好!!!");
json.put("names", Arrays.asList("小明", "小张"));
String req = Base64.getEncoder().encodeToString(S.json().toJson(json).replace("\"names\"", "names").getBytes(charset));
System.out.println("req:" + req);
StringEnreplacedy se = new StringEnreplacedy(req, charset);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
String line = resp.getStatusLine().toString();
replacedert.replacedertEquals("HTTP/1.1 200 OK", line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String ret = new String(Base64.getMimeDecoder().decode(EnreplacedyUtils.toString(resEnreplacedy)), charset);
replacedert.replacedertEquals("[\"你好!!! 小明\",\"你好!!! 小张\"]", ret);
}
19
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void db_insert() throws IOException {
String charset = "UTF-8";
HttpClient client = HttpClientBuilder.create().build();
String act = "add";
HttpPost post = new HttpPost(getUrl(act));
List<DemoUser> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
DemoUser obj = new DemoUser();
obj.setAge(r.nextInt(100));
obj.setName("名字" + r.nextInt());
obj.setId(r.nextLong());
list.add(obj);
}
Map<String, Object> json = new HashMap<>();
json.put("users", list);
StringEnreplacedy se = new StringEnreplacedy(S.json().toJson(json), charset);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
String line = resp.getStatusLine().toString();
System.out.println(line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String ret = EnreplacedyUtils.toString(resEnreplacedy, charset);
System.out.println(ret);
replacedert.replacedertEquals(list.size() + "", ret);
}
19
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void plain() throws IOException {
String charset = "GBK";
HttpClient client = HttpClientBuilder.create().build();
String act = "echo";
HttpPost post = new HttpPost(getUrl(act));
Map<String, Object> json = new HashMap<>();
json.put("echo", "你好!!!");
json.put("names", Arrays.asList("小明", "小张"));
StringEnreplacedy se = new StringEnreplacedy(S.json().toJson(json), charset);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
String line = resp.getStatusLine().toString();
replacedert.replacedertEquals("HTTP/1.1 200 OK", line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String ret = EnreplacedyUtils.toString(resEnreplacedy, charset);
replacedert.replacedertEquals("[\"你好!!! 小明\",\"你好!!! 小张\"]", ret);
}
19
Source : AesClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
// 测试加密传输并且签名
@Test
public void aes_sign() throws Exception {
String charset = "UTF-8";
String act = "aes_sign";
// 登陆,并获取加密用的key[]
HttpClient client = HttpClientBuilder.create().build();
HttpResponse resp = login(client);
String logined = EnreplacedyUtils.toString(resp.getEnreplacedy());
System.out.println("logined:" + logined);
String key_str = resp.getFirstHeader("skey").getValue();
Log.get("login").info("key:{}", key_str);
byte[] key = Base64.getMimeDecoder().decode(key_str);
// 加密数据
Map<String, Object> map = new HashMap<>();
map.put("name", "小明");
// 用AES加密
byte[] conts = Encrypt.encrypt(S.json().toJson(map).getBytes(charset), key);
// 变成base64
String req = Base64.getEncoder().encodeToString(conts);
StringEnreplacedy se = new StringEnreplacedy(req, charset);
Log.get("aes_sign").info("req:" + req);
// 生成sign,这个是需要sign的接口特有的
String sign = Encrypt.sign(S.json().toJson(map).getBytes(charset));
System.out.println("sign:" + sign);
HttpPost post = new HttpPost(getUrl(act) + "?sign=" + sign);
post.setEnreplacedy(se);
resp = client.execute(post);
String line = resp.getStatusLine().toString();
Log.get("aes_sign").info(line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String raw = EnreplacedyUtils.toString(resEnreplacedy);
Log.get("aes").info("raw resp:{}", raw);
byte[] contentBytes = Base64.getMimeDecoder().decode(raw);
String ret = new String(Encrypt.decrypt(contentBytes, key), charset);
Log.get("aes_base64").info("服务器返回:" + ret);
replacedert.replacedertEquals("hello 小明", ret);
}
19
Source : HttpPressTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void test() throws IOException, InterruptedException {
String charset = "utf-8";
HttpClient client = HttpClientBuilder.create().setMaxConnTotal(5000).setMaxConnPerRoute(1000).build();
ExecutorService executor = Executors.newFixedThreadPool(500);
HttpPost post = new HttpPost("http://localhost:8080/rest/echo");
Map<String, Object> json = new HashMap<>();
json.put("echo", "你好!!!");
json.put("names", Arrays.asList("小明", "小张"));
StringEnreplacedy se = new StringEnreplacedy(S.json().toJson(json), charset);
post.setEnreplacedy(se);
System.out.println("开始压测,请耐心等待10秒左右。。。");
long begin = System.currentTimeMillis();
int count = 100000;
AtomicLong totalRT = new AtomicLong();
AtomicLong success = new AtomicLong();
for (int i = 0; i < count; i++) {
executor.execute(() -> {
try {
long b2 = System.currentTimeMillis();
HttpResponse resp = client.execute(post);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
totalRT.addAndGet(System.currentTimeMillis() - b2);
String ret = EnreplacedyUtils.toString(resEnreplacedy, charset);
replacedert.replacedertEquals("[\"你好!!! 小明\",\"你好!!! 小张\"]", ret);
success.incrementAndGet();
} catch (Exception e) {
e.printStackTrace();
}
});
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.DAYS);
long time = System.currentTimeMillis() - begin;
replacedert.replacedertEquals(count, success.get());
System.out.println(count + "次http请求总耗时:" + time + "ms,平均每秒请求数:" + (count * 1000d / time));
System.out.println("平均每个请求耗时:" + totalRT.get() / count + "ms");
}
19
Source : HttpClientImpl.java
with Apache License 2.0
from yizhuoyan
with Apache License 2.0
from yizhuoyan
private void doWork(boolean male, int ageingYear, File photo) throws Exception {
HttpPost req = new HttpPost(URL_UPLOAD);
HttpEnreplacedy reqEnreplacedy = MultipartEnreplacedyBuilder.create().addTextBody("action", "upload").addTextBody("gender", male ? "male" : "female").addTextBody("age", String.valueOf(ageingYear)).addTextBody("drugs", "0").addBinaryBody("photofile", photo).build();
req.setEnreplacedy(reqEnreplacedy);
HttpResponse resp = client.execute(req);
if (resp.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException(resp.getStatusLine().getReasonPhrase());
}
HttpEnreplacedy respEnreplacedy = resp.getEnreplacedy();
String respString = EnreplacedyUtils.toString(respEnreplacedy);
JSONObject uploadResult = JSON.parseObject(respString);
System.out.println("上传成功!" + uploadResult);
checkImage(uploadResult);
}
19
Source : HttpPostDeliverService.java
with MIT License
from Yirendai
with MIT License
from Yirendai
public clreplaced HttpPostDeliverService implements DeliverService {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpPostDeliverService.clreplaced);
// private CloseableHttpClient httpClient;
private final CloseableHttpAsyncClient httpClient;
private final HttpPost httpPost;
public HttpPostDeliverService(final String postUrl, final int connectTimeout, final int soTimeout) {
httpClient = HttpAsyncClients.createDefault();
httpClient.start();
httpPost = new HttpPost(postUrl);
final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(soTimeout).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Content-Type", "text/html;charset=UTF-8");
}
public boolean deliver(final Span span) {
boolean ret = false;
if (span == null) {
LOGGER.error("no span!");
ret = false;
} else {
final List<Span> spanList = new ArrayList<Span>();
spanList.add(span);
ret = deliver(spanList);
}
return ret;
}
public boolean deliver(final List<Span> spanList) {
boolean ret = false;
if (CollectionUtils.isEmpty(spanList)) {
LOGGER.error("spanList is Empty!");
ret = false;
} else {
if (httpClient == null || httpPost == null) {
LOGGER.error("httpClient({}) or httpPost({}) is null", httpClient, httpPost);
ret = false;
} else {
final long startTime = System.currentTimeMillis();
final int spanSize = spanList.size();
final String spanListJson = JSON.toJSONString(spanList);
final StringEnreplacedy postingString = new StringEnreplacedy(spanListJson, "utf-8");
httpPost.setEnreplacedy(postingString);
httpClient.execute(httpPost, new FutureCallback<HttpResponse>() {
public void completed(final HttpResponse response) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[push({})] [http_status:200] [spanSize:{}] [{}ms]", spanListJson, spanSize, (System.currentTimeMillis() - startTime));
}
}
public void failed(final Exception ex) {
LOGGER.error("[push({})] [{}] [error:{}]", httpPost.getURI(), spanListJson, ex);
}
public void cancelled() {
LOGGER.error("[push({})] [http_status:cancelled] [{}ms]", spanListJson, (System.currentTimeMillis() - startTime));
}
});
ret = true;
}
}
return ret;
}
}
19
Source : HttpUtil.java
with MIT License
from yili1992
with MIT License
from yili1992
/**
* 获得HttpPost对象
*
* @param url
* 请求地址
* @param params
* 请求参数
* @param encode
* 编码方式
* @return HttpPost对象
*/
private static HttpPost getHttpPost(String url, Map<String, String> params, String encode) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
List<NameValuePair> form = new ArrayList<NameValuePair>();
for (String name : params.keySet()) {
form.add(new BasicNameValuePair(name, params.get(name)));
}
try {
UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(form, encode);
httpPost.setEnreplacedy(enreplacedy);
} catch (UnsupportedEncodingException e) {
System.out.println("UrlEncodedFormEnreplacedy Error,encode=" + encode + ",form=" + form + e);
}
}
return httpPost;
}
19
Source : HttpUtil.java
with MIT License
from yili1992
with MIT License
from yili1992
/**
* POST请求, 结果以字符串形式返回.
*
* @param url
* 请求地址
* @param params
* 请求参数
* @param reqHeader
* 请求头内容
* @param encode
* 编码方式
* @return 内容字符串
* @throws Exception
*/
public static String postUrlreplacedtring(String url, Map<String, String> params, Map<String, String> reqHeader, String encode) throws Exception {
// 开始时间
long t1 = System.currentTimeMillis();
// 获得HttpPost对象
HttpPost httpPost = getHttpPost(url, params, encode);
// 发送请求
String result = executeHttpRequest(httpPost, reqHeader);
// 结束时间
long t2 = System.currentTimeMillis();
// 返回结果
return result;
}
19
Source : HttpUtil.java
with Apache License 2.0
from YiJiuSmile
with Apache License 2.0
from YiJiuSmile
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(paramList, "utf-8");
httpPost.setEnreplacedy(enreplacedy);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EnreplacedyUtils.toString(response.getEnreplacedy(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
19
Source : HttpUtil.java
with Apache License 2.0
from YiJiuSmile
with Apache License 2.0
from YiJiuSmile
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEnreplacedy enreplacedy = new StringEnreplacedy(json, ContentType.APPLICATION_JSON);
httpPost.setEnreplacedy(enreplacedy);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EnreplacedyUtils.toString(response.getEnreplacedy(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
19
Source : HttpClientUtil.java
with Apache License 2.0
from yfh0918
with Apache License 2.0
from yfh0918
// 获取uri
private static HttpUriRequest getHttpUriRequest(HTTPRequestParameter parameter) throws Exception {
String url = NamingClient.getRealIpUrl(parameter.getUrl());
LOGGER.info(url);
HttpRequestBase request = null;
// GET
if (parameter.getRequstType() == RequstType.HTTP_GET) {
URIBuilder builder = new URIBuilder(url);
if (parameter.getRequestParams() != null) {
for (Entry<String, Object> param : parameter.getRequestParams().entrySet()) {
if (param.getValue() != null) {
builder.addParameter(param.getKey(), param.getValue().toString());
}
}
}
URI uri = builder.build();
request = new HttpGet(uri);
} else {
URI uri = URI.create(url);
HttpPost httpost = new HttpPost(uri);
if (parameter.getRequstType() == RequstType.HTTP_POST) {
// POST
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (parameter.getRequestParams() != null) {
for (Entry<String, Object> param : parameter.getRequestParams().entrySet()) {
if (param.getValue() != null) {
nvps.add(new BasicNameValuePair(param.getKey(), param.getValue().toString()));
}
}
}
httpost.setEnreplacedy(new UrlEncodedFormEnreplacedy(nvps, UTF8));
} else if (parameter.getRequstType() == RequstType.HTTP_POST_BODY) {
// 设置body
StringEnreplacedy bodyEnreplacedy = new StringEnreplacedy(parameter.getBody(), Charset.forName(UTF8));
bodyEnreplacedy.setContentEncoding(UTF8);
bodyEnreplacedy.setContentType("application/json");
httpost.setEnreplacedy(bodyEnreplacedy);
} else if (parameter.getRequstType() == RequstType.HTTP_POST_MULTIPART) {
MultipartEnreplacedyBuilder multipartEnreplacedyBuilder = MultipartEnreplacedyBuilder.create();
for (Entry<String, ContentBody> param : parameter.getRequestContentBodys().entrySet()) {
if (param.getValue() != null) {
multipartEnreplacedyBuilder.addPart(param.getKey(), param.getValue());
}
}
HttpEnreplacedy reqEnreplacedy = multipartEnreplacedyBuilder.build();
httpost.setEnreplacedy(reqEnreplacedy);
}
request = httpost;
}
// 设置其他参数
setTimeout(request, parameter.getTimeout());
setHeaderParams(request, parameter.getHeadParams());
return request;
}
19
Source : HttpClientUtils.java
with MIT License
from YeautyYE
with MIT License
from YeautyYE
/**
* 设置表单参数 主要给post使用
*
* @param param
* @param httpPost
* @throws UnsupportedEncodingException
*/
private static void setFormParam(Map<String, String> param, HttpPost httpPost) throws UnsupportedEncodingException {
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(paramList);
httpPost.setEnreplacedy(enreplacedy);
}
}
19
Source : HttpClientUtils.java
with MIT License
from YeautyYE
with MIT License
from YeautyYE
public static String doPost(String url, Map<String, String> param, String json, Map<String, String> headers, String charset, String proxyHost, Integer proxyPort) {
// 创建Http请求配置参数
RequestConfig.Builder requestBuilder = RequestConfig.custom().setConnectionRequestTimeout(2000).setConnectTimeout(2000).setSocketTimeout(2000);
HttpHost httpHost = null;
if (proxyHost != null && proxyPort != null) {
httpHost = new HttpHost(proxyHost, proxyPort);
requestBuilder.setProxy(httpHost);
}
RequestConfig requestConfig = requestBuilder.build();
// 创建httpClient
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setDefaultRequestConfig(requestConfig).setRetryHandler(new RetryHandler());
CloseableHttpClient httpClient = httpClientBuilder.build();
HttpClientContext httpClientContext = HttpClientContext.create();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 请求头
setHeaders(headers, httpPost);
// 设置参数
if (json != null) {
setJsonParam(json, httpPost);
} else {
setFormParam(param, httpPost);
}
// 执行请求
response = httpClient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EnreplacedyUtils.toString(response.getEnreplacedy(), charset);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeResponse(httpClient, response);
}
return resultString;
}
19
Source : HttpClientUtils.java
with MIT License
from YeautyYE
with MIT License
from YeautyYE
/**
* 设置json参数
*
* @param json
* @param httpPost
*/
private static void setJsonParam(String json, HttpPost httpPost) {
StringEnreplacedy enreplacedy = new StringEnreplacedy(json, ContentType.APPLICATION_JSON);
httpPost.setEnreplacedy(enreplacedy);
}
19
Source : WXPayRequest.java
with BSD 3-Clause "New" or "Revised" License
from YClimb
with BSD 3-Clause "New" or "Revised" License
from YClimb
/**
* 请求,只请求一次,不做重试
*
* @param domain
* @param urlSuffix
* @param uuid
* @param data
* @param connectTimeoutMs
* @param readTimeoutMs
* @param useCert 是否使用证书,针对退款、撤销等操作
* @return
* @throws Exception
*/
private String requestOnce(final String domain, String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert) throws Exception {
BasicHttpClientConnectionManager connManager;
if (useCert) {
// 证书
char[] preplacedword = config.getMchID().toCharArray();
InputStream certStream = config.getCertStream();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(certStream, preplacedword);
// 实例化密钥库 & 初始化密钥工厂
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, preplacedword);
// 创建 SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, new DefaultHostnameVerifier());
connManager = new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslConnectionSocketFactory).build(), null, null, null);
} else {
connManager = new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build(), null, null, null);
}
HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
String url = "https://" + domain + urlSuffix;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
httpPost.setConfig(requestConfig);
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(data, "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.addHeader("User-Agent", USER_AGENT + " " + config.getMchID());
httpPost.setEnreplacedy(postEnreplacedy);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEnreplacedy httpEnreplacedy = httpResponse.getEnreplacedy();
return EnreplacedyUtils.toString(httpEnreplacedy, "UTF-8");
}
19
Source : WXPayReport.java
with BSD 3-Clause "New" or "Revised" License
from YClimb
with BSD 3-Clause "New" or "Revised" License
from YClimb
/**
* http 请求
*
* @param data
* @param connectTimeoutMs
* @param readTimeoutMs
* @return
* @throws Exception
*/
private static String httpRequest(String data, int connectTimeoutMs, int readTimeoutMs) throws Exception {
BasicHttpClientConnectionManager connManager;
connManager = new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build(), null, null, null);
HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
HttpPost httpPost = new HttpPost(REPORT_URL);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
httpPost.setConfig(requestConfig);
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(data, "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.addHeader("User-Agent", WXPayConstants.USER_AGENT);
httpPost.setEnreplacedy(postEnreplacedy);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEnreplacedy httpEnreplacedy = httpResponse.getEnreplacedy();
return EnreplacedyUtils.toString(httpEnreplacedy, "UTF-8");
}
19
Source : HttpsUtils.java
with MIT License
from yankj12
with MIT License
from yankj12
/**
* httpClient post请求
* @param url 请求url
* @param header 头部信息
* @param param 请求参数 form提交适用
* @param enreplacedy 请求实体 json/xml提交适用
* @return 可能为空 需要处理
* @throws Exception
*/
public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEnreplacedy enreplacedy) throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
// 设置头信息
if (header != null && header.size() > 0) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求参数
if (param != null && param.size() > 0) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : param.entrySet()) {
// 给参数赋值
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEnreplacedy urlEncodedFormEnreplacedy = new UrlEncodedFormEnreplacedy(formparams, Consts.UTF_8);
httpPost.setEnreplacedy(urlEncodedFormEnreplacedy);
}
// 设置实体 优先级高
if (enreplacedy != null) {
httpPost.setEnreplacedy(enreplacedy);
}
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEnreplacedy resEnreplacedy = httpResponse.getEnreplacedy();
result = EnreplacedyUtils.toString(resEnreplacedy);
} else {
readHttpResponse(httpResponse);
}
} catch (Exception e) {
throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
See More Examples