1.需要引入的jar包。
使用idea导入com.budjb:http-requests-httpcomponents-client:2.0.2,如下图:
2.工具类HttpUtil.java,代码如下:
package com.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpUtil {
private static String charset = "utf-8";
private static CloseableHttpClient httpClient = HttpClients.createDefault();
@SuppressWarnings({"unchecked", "rawtypes"})
public static String doPost(String url, String jsonStr) {
HttpPost httpPost;
String result = null;
try {
httpPost = new HttpPost(url);
// 设置参数
httpPost.setHeader("content-Type","application/json;charset=UTF-8");
StringEntity entity = new StringEntity(jsonStr);
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) {
ex.printStackTrace();
}
return result;
}
}