Apache HttpComponents 简单使用

官网

参考 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");
        // 默认 Content-Type
        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");//发送json需要设置contentType
        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 {
    
    }

三、关闭 Debug 日志打印

如果你只使用 main 方法调用 Api 接口,控制台会打印很多无用日志(如果是 Springboot 项目可以配置日志配置文件,如:loback.xml),main 方法可以通过调整日志级别关闭 Debug 日志打印

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

main 方法调用控制台打印无用日志
在这里插入图片描述
调整日志级别

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;
public class TestBlob {
    
    
    public static void main(String[] args) {
    
    
        ((LoggerContext) LoggerFactory.getILoggerFactory())
                .getLoggerList()
                .forEach(logger -> logger.setLevel(Level.ERROR));

        System.out.println(getArticleCount());
        System.out.println(ArrayUtils.toString(getUrl()));
    }
}    

猜你喜欢

转载自blog.csdn.net/qq_43842093/article/details/127329714