1.maven坐标
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
2.初始化httpclient
CloseableHttpClient与HttpClient的关系
public abstract class CloseableHttpClient implements HttpClient, Closeable{}
三种创建HttpClient客户端
1.CloseableHttpClient httpclient = HttpClients.createDefault();
2.DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());
3.HttpClient httpclient = HttpClients.createDefault();
3.上代码
public class HttpClientUtil {
public static String doPost(String url, String jsonParam, String charset){
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
// 初始化客户端
httpClient = HttpClients.createDefault();
// 创建post请求
httpPost = new HttpPost(url);
//设置参数
StringEntity stringEntity = new StringEntity(jsonParam,charset);
stringEntity.setContentEncoding(charset);
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
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;
}
}
4.参考地址
https://www.cnblogs.com/kiko2014551511/p/11609853.html