public static String post(String url, Map paramMap) throws ClientProtocolException, IOException,Exception {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
//设置认证信息
JSONObject json=new JSONObject(paramMap);
httpPost.setConfig(RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(3000).setSocketTimeout(5000).build());
List formparams = setHttpParams(paramMap);
UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8");
//通过setEntity()设置参数给post
httpPost.setEntity(param);
//利用httpClient的execute()方法发送请求并且获取返回参数
HttpResponse response = httpClient.execute(httpPost);
String httpEntityContent = getHttpEntityContent(response);
httpPost.abort();
return httpEntityContent;
}
/**
* 设置请求参数
* @param
* @return
*/
private static List setHttpParams(Map paramMap) {
List formparams = new ArrayList<>();
Set> set = paramMap.entrySet();
for (Map.Entry entry : set) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
return formparams;
}
/**
* 获得响应HTTP实体内容
* @param response
* @return
* @throws java.io.IOException
* @throws java.io.UnsupportedEncodingException
*/
private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
//通过HttpResponse 的getEntity()方法获取返回信息
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = br.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line + "\n");
line = br.readLine();
}
br.close();
is.close();
return sb.toString();
}
return "";
}