HttpClient4.2 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请求,不对返回的响应作处理

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.vectoryi.fluent;  
  2.   
  3. import java.io.File;  
  4.   
  5. import org.apache.http.HttpHost;  
  6. import org.apache.http.HttpVersion;  
  7. import org.apache.http.client.fluent.Form;  
  8. import org.apache.http.client.fluent.Request;  
  9. import org.apache.http.entity.ContentType;  
  10.   
  11.   
  12. public class FluentRequests {  
  13.   
  14.     public static void main(String[] args)throws Exception {  
  15.         //执行一个GET请求,同时设置Timeout参数并将响应内容作为String返回  
  16.         Request.Get("http://blog.csdn.net/vector_yi")  
  17.                 .connectTimeout(1000)  
  18.                 .socketTimeout(1000)  
  19.                 .execute().returnContent().asString();  
  20.   
  21.         //以Http/1.1版本协议执行一个POST请求,同时配置Expect-continue handshake达到性能调优,  
  22.         //请求中包含String类型的请求体并将响应内容作为byte[]返回  
  23.         Request.Post("http://blog.csdn.net/vector_yi")  
  24.                 .useExpectContinue()  
  25.                 .version(HttpVersion.HTTP_1_1)  
  26.                 .bodyString("Important stuff", ContentType.DEFAULT_TEXT)  
  27.                 .execute().returnContent().asBytes();  
  28.   
  29.   
  30.         //通过代理执行一个POST请求并添加一个自定义的头部属性,请求包含一个HTML表单类型的请求体  
  31.         //将返回的响应内容存入文件  
  32.         Request.Post("http://blog.csdn.net/vector_yi")  
  33.                 .addHeader("X-Custom-header""stuff")  
  34.                 .viaProxy(new HttpHost("myproxy"8080))  
  35.                 .bodyForm(Form.form().add("username""vip").add("password""secret").build(), Charset.forName("UTF-8"))  
  36.                 .execute().saveContent(new File("result.dump"));  
  37.     }  
  38.   
  39. }  

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.vectoryi.fluent;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.Queue;  
  5. import java.util.concurrent.ExecutionException;  
  6. import java.util.concurrent.ExecutorService;  
  7. import java.util.concurrent.Executors;  
  8. import java.util.concurrent.Future;  
  9.   
  10. import org.apache.http.client.fluent.Async;  
  11. import org.apache.http.client.fluent.Content;  
  12. import org.apache.http.client.fluent.Request;  
  13. import org.apache.http.concurrent.FutureCallback;  
  14.   
  15.   
  16. public class FluentAsync {  
  17.   
  18.     public static void main(String[] args)throws Exception {  
  19.         // 利用线程池  
  20.         ExecutorService threadpool = Executors.newFixedThreadPool(2);  
  21.         Async async = Async.newInstance().use(threadpool);  
  22.   
  23.         Request[] requests = new Request[] {  
  24.                 Request.Get("http://www.google.com/"),  
  25.                 Request.Get("http://www.yahoo.com/"),  
  26.                 Request.Get("http://www.apache.com/"),  
  27.                 Request.Get("http://www.apple.com/")  
  28.         };  
  29.   
  30.   
  31.         Queue<Future<Content>> queue = new LinkedList<Future<Content>>();  
  32.         // 异步执行GET请求  
  33.         for (final Request request: requests) {  
  34.             Future<Content> future = async.execute(request, new FutureCallback<Content>() {  
  35.   
  36.                 public void failed(final Exception ex) {  
  37.                     System.out.println(ex.getMessage() + ": " + request);  
  38.                 }  
  39.   
  40.                 public void completed(final Content content) {  
  41.                     System.out.println("Request completed: " + request);  
  42.                 }  
  43.   
  44.                 public void cancelled() {  
  45.                 }  
  46.   
  47.             });  
  48.             queue.add(future);  
  49.         }  
  50.   
  51.         while(!queue.isEmpty()) {  
  52.             Future<Content> future = queue.remove();  
  53.             try {  
  54.                 future.get();  
  55.             } catch (ExecutionException ex) {  
  56.             }  
  57.         }  
  58.         System.out.println("Done");  
  59.         threadpool.shutdown();  
  60.     }  
  61.   
  62. }  

三、更快速地启动请求

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.vectoryi.fluent;  
  2.   
  3. import org.apache.http.client.fluent.Form;  
  4. import org.apache.http.client.fluent.Request;  
  5.   
  6. public class FluentQuickStart {  
  7.   
  8.     public static void main(String[] args) throws Exception {  
  9.   
  10.         Request.Get("http://targethost/homepage")  
  11.             .execute().returnContent();  
  12.         Request.Post("http://targethost/login")  
  13.             .bodyForm(Form.form().add("username",  "vip").add("password",  "secret").build())  
  14.             .execute().returnContent();  
  15.     }  
  16. }  

四、处理Response

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.vectoryi.fluent;  
  2.   
  3. import java.io.IOException;  
  4. import java.nio.charset.Charset;  
  5.   
  6. import javax.xml.parsers.DocumentBuilder;  
  7. import javax.xml.parsers.DocumentBuilderFactory;  
  8. import javax.xml.parsers.ParserConfigurationException;  
  9.   
  10. import org.apache.http.Consts;  
  11. import org.apache.http.HttpEntity;  
  12. import org.apache.http.HttpResponse;  
  13. import org.apache.http.StatusLine;  
  14. import org.apache.http.client.ClientProtocolException;  
  15. import org.apache.http.client.HttpResponseException;  
  16. import org.apache.http.client.ResponseHandler;  
  17. import org.apache.http.client.fluent.Request;  
  18. import org.apache.http.entity.ContentType;  
  19. import org.w3c.dom.Document;  
  20. import org.xml.sax.SAXException;  
  21.   
  22.   
  23. public class FluentResponseHandling {  
  24.   
  25.     public static void main(String[] args)throws Exception {  
  26.         Document result = Request.Get("http://www.baidu.com")  
  27.                 .execute().handleResponse(new ResponseHandler<Document>() {  
  28.   
  29.             public Document handleResponse(final HttpResponse response) throws IOException {  
  30.                 StatusLine statusLine = response.getStatusLine();  
  31.                 HttpEntity entity = response.getEntity();  
  32.                 if (statusLine.getStatusCode() >= 300) {  
  33.                     throw new HttpResponseException(  
  34.                             statusLine.getStatusCode(),  
  35.                             statusLine.getReasonPhrase());  
  36.                 }  
  37.                 if (entity == null) {  
  38.                     throw new ClientProtocolException("Response contains no content");  
  39.                 }  
  40.                 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();  
  41.                 try {  
  42.                     DocumentBuilder docBuilder = dbfac.newDocumentBuilder();  
  43.                     ContentType contentType = ContentType.getOrDefault(entity);  
  44.                     if (!contentType.equals(ContentType.APPLICATION_XML)) {  
  45.                         throw new ClientProtocolException("Unexpected content type:" + contentType);  
  46.                     }  
  47.                     Charset charset = contentType.getCharset();  
  48.                     if (charset == null) {  
  49.                         charset = Consts.ISO_8859_1;  
  50.                     }  
  51.                     return docBuilder.parse(entity.getContent(), charset.name());  
  52.                 } catch (ParserConfigurationException ex) {  
  53.                     throw new IllegalStateException(ex);  
  54.                 } catch (SAXException ex) {  
  55.                     throw new ClientProtocolException("Malformed XML document", ex);  
  56.                 }  
  57.             }  
  58.   
  59.             });  
  60.         // 处理得到的result  
  61.         System.out.println(result);  
  62.     }  
  63.   
  64. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值