HttpClient 4.3详细教程之快速API

5.1. Easy to use facade API

HttpClient从4.2开始支持快速api。快速api仅仅实现了HttpClient的基本功能,它只要用于一些不需要灵活性的简单场景。例如,快速api不需要用户处理连接管理和资源释放。

下面是几个使用快速api的例子:

[java]  view plain copy
  1. // Execute a GET with timeout settings and return response content as String.  
  2. Request.Get("http://somehost/")  
  3.         .connectTimeout(1000)  
  4.         .socketTimeout(1000)  
  5.         .execute().returnContent().asString();  

[java]  view plain copy
  1. // Execute a POST with the 'expect-continue' handshake, using HTTP/1.1,  
  2. // containing a request body as String and return response content as byte array.  
  3. Request.Post("http://somehost/do-stuff")  
  4.         .useExpectContinue()  
  5.         .version(HttpVersion.HTTP_1_1)  
  6.         .bodyString("Important stuff", ContentType.DEFAULT_TEXT)  
  7.         .execute().returnContent().asBytes();  

[java]  view plain copy
  1. // Execute a POST with a custom header through the proxy containing a request body  
  2. // as an HTML form and save the result to the file  
  3. Request.Post("http://somehost/some-form")  
  4.         .addHeader("X-Custom-header""stuff")  
  5.         .viaProxy(new HttpHost("myproxy"8080))  
  6.         .bodyForm(Form.form().add("username""vip").add("password""secret").build())  
  7.         .execute().saveContent(new File("result.dump"));  

如果需要在指定的安全上下文中执行某些请求,我们也可以直接使用Exector,这时候用户的认证信息就会被缓存起来,以便后续的请求使用。
[java]  view plain copy
  1. Executor executor = Executor.newInstance()  
  2.         .auth(new HttpHost("somehost"), "username""password")  
  3.         .auth(new HttpHost("myproxy"8080), "username""password")  
  4.         .authPreemptive(new HttpHost("myproxy"8080));  
  5.   
  6. executor.execute(Request.Get("http://somehost/"))  
  7.         .returnContent().asString();  
  8.   
  9. executor.execute(Request.Post("http://somehost/do-stuff")  
  10.         .useExpectContinue()  
  11.         .bodyString("Important stuff", ContentType.DEFAULT_TEXT))  
  12.         .returnContent().asString();  

5.1.1. 响应处理

一般情况下,HttpClient的快速api不用用户处理连接管理和资源释放。但是,这样的话,就必须在内存中缓存这些响应消息。为了避免这一情况,建议使用使用ResponseHandler来处理Http响应。

[java]  view plain copy
  1. Document result = Request.Get("http://somehost/content")  
  2.         .execute().handleResponse(new ResponseHandler<Document>() {  
  3.   
  4.     public Document handleResponse(final HttpResponse response) throws IOException {  
  5.         StatusLine statusLine = response.getStatusLine();  
  6.         HttpEntity entity = response.getEntity();  
  7.         if (statusLine.getStatusCode() >= 300) {  
  8.             throw new HttpResponseException(  
  9.                     statusLine.getStatusCode(),  
  10.                     statusLine.getReasonPhrase());  
  11.         }  
  12.         if (entity == null) {  
  13.             throw new ClientProtocolException("Response contains no content");  
  14.         }  
  15.         DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();  
  16.         try {  
  17.             DocumentBuilder docBuilder = dbfac.newDocumentBuilder();  
  18.             ContentType contentType = ContentType.getOrDefault(entity);  
  19.             if (!contentType.equals(ContentType.APPLICATION_XML)) {  
  20.                 throw new ClientProtocolException("Unexpected content type:" +  
  21.                     contentType);  
  22.             }  
  23.             String charset = contentType.getCharset();  
  24.             if (charset == null) {  
  25.                 charset = HTTP.DEFAULT_CONTENT_CHARSET;  
  26.             }  
  27.             return docBuilder.parse(entity.getContent(), charset);  
  28.         } catch (ParserConfigurationException ex) {  
  29.             throw new IllegalStateException(ex);  
  30.         } catch (SAXException ex) {  
  31.             throw new ClientProtocolException("Malformed XML document", ex);  
  32.         }  
  33.     }  
  34.   
  35.     });  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值