使用HttpClient发送http请求
一、引入httpclient.jar
和fastjson.jar
依赖jar
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
如果依赖下载失败,需要降低版本
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
二、发送请求
1、创建httpclient
CloseableHttpClient client = HttpClients.createDefault();
2、创建http请求
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpHead httpHead = new HttpHead(url);
HttpDelete httpDelete = new HttpDelete(url);
HttpPatch httpPatch = new HttpPatch(url);
HttpPut httpPut = new HttpPut(url);
HttpOptions httpOptions = new HttpOptions(url);
3、添加参数
1)GET
请求传参
//直接把参数拼接到url后面即可
String url = "http://127.0.0.1/api/user/login?mobile_phone=17722532471&pwd=123456789";
-------------------------------------------------------
//使用`URIBuilder`构建`URL`
Map<String, Object> param = new HashMap<>();
param.put("mobile_phone", "17722532471");
param.put("pwd", "123456789");
//创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
//创建http Get请求,把URIBuilder对象传入
HttpGet httpGet = new HttpGet(uri);
2)POST
请求传参
//传入的是map集合
Map<String, Object> param = new HashMap<>();
param.put("mobile_phone", "17722523223");
param.put("pwd", "123456789");
//把map集合转换成json格式传参
String jsonString = JSON.toJSONString(param);
httpPost.setEntity(new StringEntity(jsonString));
--------------------------------------------------------------------------------
//传入的是json字符串
String jsonParam = "{\"mobile_phone\":\"17722532470\",\"pwd\":\"123456789\"}";
//通过toJSON把参数转成json字符串
String jsonString = (String) JSON.toJSON(jsonParam);
httpPost.setEntity(new StringEntity(jsonString));
4、添加请求头
Map<String, String> header = new HashMap<>();
header.put("k", "v");
header.put("k", "v");
for (String key : header.keySet()) {
httpPost.setHeader(new BasicHeader(key, header.get(key)));
}
5、执行请求
CloseableHttpResponse response = client.execute(httpPost);
6、获取响应头
int statusCode = response.getStatusLine().getStatusCode();
7、获取响应实体
if (200 == statusCode) {
//字符串编码
String s = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(s);
}
8、关闭流
response.close();
client.close();