/**
* post请求(用于请求json格式的参数)
*
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map<String, String> params,Boolean flag)
throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
String charSet = "UTF-8";
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
StringEntity strEntity=null;
Set<String> set = params.keySet();
for (String key : set) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
strEntity = new StringEntity(params.get(key),charSet);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps);
entity.setContentEncoding(charSet);
if (flag) {
httpPost.setEntity(strEntity);
}else{
httpPost.setEntity(entity);
}
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
} else {
logger.error("请求返回:" + state + "(" + url + ")");
}
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
post请求
最新推荐文章于 2024-05-27 21:41:47 发布