1.导入maven依赖
<!-- 模拟客户端 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
2.工具类
public class HttpClientUtils {
/**
* 模拟发送doget请求
* @param url
* @return
*/
public static JSONObject doGet(String url) throws IOException {
JSONObject jsonObject=null;
//指定请求方式
HttpGet httpGet = new HttpGet(url);
//获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//执行发送请求并响应结果
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
//请求成功,返回数据
HttpEntity entity = httpResponse.getEntity();
//将请求中的响应结果换成字符并加上字符集设置
String str = EntityUtils.toString(entity,"utf-8");
//将数据转换为json
jsonObject= new JSONObject(str);
}
return jsonObject;
}
/**
*
* @param url
* @param data 传送数据
* @return
*/
public static JSONObject doPost(String url ,String data) throws IOException {
JSONObject jsonObject=null;
HttpPost httpPost = new HttpPost(url);
//post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(new StringEntity(data,"utf-8"));
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
String str = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
//将数据转换为json
jsonObject= new JSONObject(str);
}
return jsonObject;
}
}