官网
https://hc.apache.org/httpcomponents-client-4.5.x/index.html
参考 https://www.cnblogs.com/lrzy/articles/15667814.html
一、简介
Apache Commons HttpClient(或被称为 Apache HttpClient 3.x)、Apache HttpComponents Client(或被称为 Apache HttpClient 4.x)
HttpComponents 项目就是专门设计来简化 HTTP 客户端与服务器进行各种通讯编程。
现在的 HttpComponents 包含多个子项目
HttpComponents Core、HttpComponents Client、HttpComponents AsyncClient、Commons HttpClient
主要的功能
- 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
- 支持自动转向
- 支持 HTTPS 协议
- 支持代理服务器等
- 支持Cookie
1、导入依赖
最新版本 4.5.13
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
请求地址:http://127.0.0.1:8080/HttpClient/get/params?id=123456&name=admin
@Autowired
HttpClientComponentsController httpClientComponentsController;
@Test
public void getMethod() throws IOException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 123456);
jsonObject.put("name", "admin");
StringBuilder url = new StringBuilder("http://127.0.0.1:8080/HttpClient/get/params");
url.append("?");
for (String s : jsonObject.keySet()) {
url.append(s).append("=").append(jsonObject.get(s)).append("&");
}
String substring = url.substring(0, url.length() - 1);
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(new HttpGet(substring));
System.out.println(EntityUtils.toString(closeableHttpResponse.getEntity()));
}
java 接口
@GetMapping("/get/params")
public JSONObject getParams(@RequestParam String id, @RequestParam("name") String userName){}
二、post 请求
1、post 请求传递 x-www-form-urlencoded 参数
请求地址:http://127.0.0.1:8080/HttpClient/post/params/x-www UrlEncodedFormEntity 继承 StringEntity 构造方法默认 CONTENT_TYPE = "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" 所以传递参数可以在 url 后使用 & 拼接参数
@Test
public void getPost() throws IOException {
String url = "http://127.0.0.1:8080/HttpClient/post/params/x-www";
List<NameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("name", "admin"));
form.add(new BasicNameValuePair("password", "123456"));
HttpEntity reqEntity = new UrlEncodedFormEntity(form, "utf-8");
Header header = new BasicHeader("Connection", "Keep-Alive");
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(reqEntity);
httpPost.setHeader(header);
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;");
httpPost.setConfig(requestConfig);
HttpClient httpClient = HttpClients.custom().build();
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
}
java 接口
@PostMapping("/post/params/x-www")
public JSONObject postParams(String name, String password) {}
2、post/get 请求传递 json 参数
StringEntity 可以传递 json 参数,默认 CONTENT_TYPE = "text/plain; charset=ISO-8859-1“ 请求地址:http://127.0.0.1:8080/HttpClient/post/params/json
@Test
public void getPostFormData() throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("account", "admin");
map.put("password", "123456");
JSONObject jsonObject = new JSONObject(map);
String url = "http://127.0.0.1:8080/HttpClient/post/params/json";
StringEntity se = new StringEntity(jsonObject.toJSONString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(se);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
log.info(EntityUtils.toString(response.getEntity()));
}
java 接口
@PostMapping("/post/params/json")
public JSONObject postParams(@RequestBody Map<String, Object> map) {}
3、post 请求传递 multipart/form-data 参数(含文件)
传递 multipart/form-data 参数需要导入 httpmime 依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
请求地址:http://127.0.0.1:8080/okhttp3/post/params_from_async
@Test
public void getPostFormFile() throws IOException {
File file = new File("C:\\Users\\Administrator\\Pictures\\小程序\\126.jpg");
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("file", file, ContentType.IMAGE_JPEG, "126.jpg");
multipartEntityBuilder.addTextBody("name", "admin", ContentType.TEXT_PLAIN);
multipartEntityBuilder.addTextBody("password", "123456", ContentType.TEXT_PLAIN);
HttpEntity httpEntity = multipartEntityBuilder.build();
String url = "http://127.0.0.1:8080/okhttp3/post/params_from_async";
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(httpEntity);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
log.info(EntityUtils.toString(response.getEntity()));
}
java 接口
@PostMapping("/post/params_from_async")
public JSONObject postParamsFromAsync(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws InterruptedException, IOException, ServletException {}
|