HttpClient4.5.8 Fluent API简单使用

最近在Apache Httpcomponents中里查找资料意外发现了HC(HttpClient简写)发送http请求的一种简写形式,当时看到的场面时这样的:在这里插入图片描述
瞬间感觉被征服了。翻译一下上述内容:同样的请求也可以使用更简单、更灵活、更流畅的API来执行。官方API文档:http://hc.apache.org/httpcomponents-client-ga/fluent-hc/apidocs/index.html

一、添加依赖
下面开始尝试一下怎么使用这个API吧,先得引入依赖,官网有介绍,直接复制到项目的pom.xml文档中即可:
在这里插入图片描述

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
            <version>4.5.8</version>
</dependency>

二、执行简单的http请求

1.Get请求

@Test
    public void testGet(){
        try {
            String response = Request.Get("https://reqres.in//api/users?page=2")
                    .execute()
                    .returnContent()
                    .asString();
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

控制台输出:
在这里插入图片描述
2. Post请求

@Test
    public void testPost() {
        try {
            String response = Request.Post("https://reqres.in/api/users")
                    .addHeader("Content-Type","application/x-www-form-urlencoded")
                    .bodyForm(Form.form().add("name","chenfeng").add("job","tester").build())
                    .execute()
                    .returnContent()
                    .asString();
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

控制台输出:在这里插入图片描述
3.利用线程池发送异步请求

 @Test
    public void testThreadPool() {
        // 初始化线程池
        ExecutorService service = Executors.newFixedThreadPool(2);
        Async async = Async.newInstance().use(service);

        Request[] requests = new Request[]{
                Request.Get("https://reqres.in/api/users?page=1"),
                Request.Get("https://reqres.in/api/users?page=2"),
                Request.Get("https://reqres.in/api/users?page=3"),
                Request.Get("https://reqres.in/api/users?page=4")
        };

        Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
        // 异步执行GET请求
        for (final Request request : requests) {
            Future<Content> future = async.execute(request, new FutureCallback<Content>() {
                public void completed(Content content) {
                    System.out.println(request + "\r\nRequest response:" + content);
                }

                public void failed(Exception e) {
                    System.out.println(e.getMessage() + ": " + request);
                }

                public void cancelled() {

                }
            });
            queue.add(future);
        }

        while (!queue.isEmpty()) {
            Future<Content> future = queue.remove();
            try {
                future.get();
            } catch (ExecutionException ex) {
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

3.控制台输出:
在这里插入图片描述

发布了18 篇原创文章 · 获赞 6 · 访问量 3234

猜你喜欢

转载自blog.csdn.net/asd0654123/article/details/90554405