HttpClient4.2流式API:链式调用与响应处理优化

相比于HttpClient 之前的版本,HttpClient 4.2 提供了一组基于流接口(fluent interface)概念的更易使用的API,即Fluent API. 为了方便使用,Fluent API只暴露了一些最基本的HttpClient功能。这样,Fluent API就将开发者从连接管理、资源释放等繁杂的操作中解

                相比于httpclient 之前的版本,httpclient 4.2 提供了一组基于流接口(fluent interface)概念的更易使用的api,即fluent api.

                为了方便使用,Fluent API只暴露了一些最基本的HttpClient功能。这样,Fluent API就将开发者从连接管理、资源释放等繁杂的操作中解放出来,从而更易进行一些HttpClient的简单操作。

http://blog.csdn.net/vector_yi/article/details/24298629

                还是利用具体例子来说明吧。

以下是几个使用Fluent API的代码样例:

一、最基本的http请求功能

执行Get、Post请求,不对返回的响应作处理

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

package com.vectoryi.fluent;

 

import java.io.File;

 

import org.apache.http.HttpHost;

import org.apache.http.HttpVersion;

import org.apache.http.client.fluent.Form;

import org.apache.http.client.fluent.Request;

import org.apache.http.entity.ContentType;

 

 

public class FluentRequests {

 

    public static void main(String[] args)throws Exception {

        //执行一个GET请求,同时设置Timeout参数并将响应内容作为String返回

        Request.Get("http://blog.csdn.net/vector_yi")

                .connectTimeout(1000)

                .socketTimeout(1000)

                .execute().returnContent().asString();

 

        //以Http/1.1版本协议执行一个POST请求,同时配置Expect-continue handshake达到性能调优,

        //请求中包含String类型的请求体并将响应内容作为byte[]返回

        Request.Post("http://blog.csdn.net/vector_yi")

                .useExpectContinue()

                .version(HttpVersion.HTTP_1_1)

                .bodyString("Important stuff", ContentType.DEFAULT_TEXT)

                .execute().returnContent().asBytes();

 

 

        //通过代理执行一个POST请求并添加一个自定义的头部属性,请求包含一个HTML表单类型的请求体

        //将返回的响应内容存入文件

        Request.Post("http://blog.csdn.net/vector_yi")

                .addHeader("X-Custom-header", "stuff")

                .viaProxy(new HttpHost("myproxy", 8080))

                .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())

                .execute().saveContent(new File("result.dump"));

    }

 

}


二、在后台线程中异步执行多个请求

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

package com.vectoryi.fluent;

 

import java.util.LinkedList;

import java.util.Queue;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

 

import org.apache.http.client.fluent.Async;

import org.apache.http.client.fluent.Content;

import org.apache.http.client.fluent.Request;

import org.apache.http.concurrent.FutureCallback;

 

 

public class FluentAsync {

 

    public static void main(String[] args)throws Exception {

        // 利用线程池

        ExecutorService threadpool = Executors.newFixedThreadPool(2);

        Async async = Async.newInstance().use(threadpool);

 

        Request[] requests = new Request[] {

                Request.Get("http://www.google.com/"),

                Request.Get("http://www.yahoo.com/"),

                Request.Get("http://www.apache.com/"),

                Request.Get("http://www.apple.com/")

        };

 

 

        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 failed(final Exception ex) {

                    System.out.println(ex.getMessage() + ": " + request);

                }

 

                public void completed(final Content content) {

                    System.out.println("Request completed: " + request);

                }

 

                public void cancelled() {

                }

 

            });

            queue.add(future);

        }

 

        while(!queue.isEmpty()) {

            Future<Content> future = queue.remove();

            try {

                future.get();

            } catch (ExecutionException ex) {

            }

        }

        System.out.println("Done");

        threadpool.shutdown();

    }

 

}


三、更快速地启动请求

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package com.vectoryi.fluent;

 

import org.apache.http.client.fluent.Form;

import org.apache.http.client.fluent.Request;

 

public class FluentQuickStart {

 

    public static void main(String[] args) throws Exception {

 

        Request.Get("http://targethost/homepage")

            .execute().returnContent();

        Request.Post("http://targethost/login")

            .bodyForm(Form.form().add("username""vip").add("password""secret").build())

            .execute().returnContent();

    }

}


四、处理Response

在本例中是利用xmlparsers来解析返回的ContentType.APPLICATION_XML类型的内容。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

package com.vectoryi.fluent;

 

import java.io.IOException;

import java.nio.charset.Charset;

 

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

 

import org.apache.http.Consts;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.StatusLine;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpResponseException;

import org.apache.http.client.ResponseHandler;

import org.apache.http.client.fluent.Request;

import org.apache.http.entity.ContentType;

import org.w3c.dom.Document;

import org.xml.sax.SAXException;

 

 

public class FluentResponseHandling {

 

    public static void main(String[] args)throws Exception {

        Document result = Request.Get("http://www.baidu.com")

                .execute().handleResponse(new ResponseHandler<Document>() {

 

            public Document handleResponse(final HttpResponse response) throws IOException {

                StatusLine statusLine = response.getStatusLine();

                HttpEntity entity = response.getEntity();

                if (statusLine.getStatusCode() >= 300) {

                    throw new HttpResponseException(

                            statusLine.getStatusCode(),

                            statusLine.getReasonPhrase());

                }

                if (entity == null) {

                    throw new ClientProtocolException("Response contains no content");

                }

                DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();

                try {

                    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

                    ContentType contentType = ContentType.getOrDefault(entity);

                    if (!contentType.equals(ContentType.APPLICATION_XML)) {

                        throw new ClientProtocolException("Unexpected content type:" + contentType);

                    }

                    Charset charset = contentType.getCharset();

                    if (charset == null) {

                        charset = Consts.ISO_8859_1;

                    }

                    return docBuilder.parse(entity.getContent(), charset.name());

                } catch (ParserConfigurationException ex) {

                    throw new IllegalStateException(ex);

                } catch (SAXException ex) {

                    throw new ClientProtocolException("Malformed XML document", ex);

                }

            }

 

            });

        // 处理得到的result

        System.out.println(result);

    }

 

}




QR Code
微信扫一扫,欢迎咨询~

联系我们
武汉格发信息技术有限公司
湖北省武汉市经开区科技园西路6号103孵化器
电话:155-2731-8020 座机:027-59821821
邮件:tanzw@gofarlic.com
Copyright © 2023 Gofarsoft Co.,Ltd. 保留所有权利
遇到许可问题?该如何解决!?
评估许可证实际采购量? 
不清楚软件许可证使用数据? 
收到软件厂商律师函!?  
想要少购买点许可证,节省费用? 
收到软件厂商侵权通告!?  
有正版license,但许可证不够用,需要新购? 
联系方式 155-2731-8020
预留信息,一起解决您的问题
* 姓名:
* 手机:

* 公司名称:

姓名不为空

手机不正确

公司不为空