4.2版本的 HttpClient 带来了一组非常容易使用的流式 API(Fluent API) 接口。暴露的流式API(Fluent API) 接口中仅仅是 HttpClient 最基本的一些功能,这些接口是在不需要使用 HttpClient 丰富的灵活性时,为了一些简单的功能而准备的。 例如:流式接口(Fluent API) 增加了使用者对连接的管理和资源的分配上的便利性。这里有一系列通过 HttpClient 流式接口(Fluent API) 执行 HTTP 请求的示例:
// Execute a GET with timeout settings and return response content as String. Request.Get("http://somehost/") .connectTimeout(1000) .socketTimeout(1000) .execute().returnContent().asString(); // Execute a POST with the 'expect-continue' handshake, using HTTP/1.1, // containing a request body as String and return response content as byte array. Request.Post("http://somehost/do-stuff") .useExpectContinue() .version(HttpVersion.HTTP_1_1) .bodyString("Important stuff", ContentType.DEFAULT_TEXT) .execute().returnContent().asBytes(); // Execute a POST with a custom header through the proxy containing a request body // as an HTML form and save the result to the file Request.Post("http://somehost/some-form") .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"));使用 Executor 在特定的需要安全认证的上下文中请求时,认证信息可以被缓存起来,这样后来的请求也可以重复使用认证信息了。
Executor executor = Executor.newInstance() .auth(new HttpHost("somehost"), "username", "password") .auth(new HttpHost("myproxy", 8080), "username", "password") .authPreemptive(new HttpHost("myproxy", 8080)); executor.execute(Request.Get("http://somehost/")) .returnContent().asString(); executor.execute(Request.Post("http://somehost/do-stuff") .useExpectContinue() .bodyString("Important stuff", ContentType.DEFAULT_TEXT)) .returnContent().asString();流式接口(Fluent API) 增加了使用者对连接的管理和资源的分配上的便利性。在许多场景下,在内存中缓存过多的响应内容也会让它付出了相应的代价。因此它推荐使用 ResponseHandler 来处理 HTTP 响应以此来避免在内存中缓存响应内容。
Document result = Request.Get("http://somehost/content") .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); } String charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } return docBuilder.parse(entity.getContent(), charset); } catch (ParserConfigurationException ex) { throw new IllegalStateException(ex); } catch (SAXException ex) { throw new ClientProtocolException("Malformed XML document", ex); } } });转载自 并发编程网 - ifeve.com
相关资源:敏捷开发V1.0.pptx