很多时候请求也有head等附加参数的时候,封装了一个使用
/**
* post
* @param url
* @param map
* @param charset
* @param headers
* @return
*/
public static String postByForm(String url, Map<String, String> map,String charset,Map<String, String> headers){
HttpClient httpClient = HttpClientBuilder.create().build();
String result = null;
try {
HttpPost httpPost = new HttpPost(url);
// 设置头部
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
if(headers != null) {
Iterator headersIterator = headers.entrySet().iterator();
while (headersIterator.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>) headersIterator.next();
httpPost.addHeader(elem.getKey(), elem.getValue());
}
}
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception ex) {
log.error("网络请求异常:{}",ex);
}
return result;
}