一、maven引入apache
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
二、封装post请求方法
public static String httpPost(String url,Map map){
// 返回body
String body = null;
// 获取链接客户端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse=null;
// 二、建立一个HttpPost请求
HttpPost post = new HttpPost(url);
// 五、设置header信息
/**header中通用属性*/
post.setHeader("Accept","*/*");
post.setHeader("Accept-Encoding","gzip, deflate");
post.setHeader("Cache-Control","no-cache");
post.setHeader("Connection", "keep-alive");
post.setHeader("Content-Type", "application/json;charset=UTF-8");
/**业务参数*/
post.setHeader("test1","test1");
post.setHeader("test2",2);
// 设置参数
if (map != null) {
//System.out.println(JSON.toJSONString(map));
try {
StringEntity entity1=new StringEntity(JSON.toJSONString(map),"UTF-8");
entity1.setContentEncoding("UTF-8");
entity1.setContentType("application/json");
post.setEntity(entity1);
// 七、执行post请求操做,并拿到结果
httpResponse = httpClient.execute(post);
// 获取结果实体
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
}
try {
httpResponse.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return body;
}
三、封装GET请求方法
public static String httpGet(String url){
// 获取链接客户端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse=null;
String finalString = null;
HttpGet httpGet = new HttpGet(url);
/**公共参数添加至httpGet*/
/**header中通用属性*/
httpGet.setHeader("Accept","*/*");
httpGet.setHeader("Accept-Encoding","gzip, deflate");
httpGet.setHeader("Cache-Control","no-cache");
httpGet.setHeader("Connection", "keep-alive");
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
/**业务参数*/