150
技術社區[雲棲]
《HttpClient 官方文檔》第五章 Fluent API
第五章:流式 API
5.1 易用 API 接口
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("https://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("https://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("https://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("https://somehost/"))
.returnContent().asString();
executor.execute(Request.Post("https://somehost/do-stuff")
.useExpectContinue()
.bodyString("Important stuff", ContentType.DEFAULT_TEXT))
.returnContent().asString();
5.1.1. 響應處理
流式接口(Fluent API) 增加了使用者對連接的管理和資源的分配上的便利性。在許多場景下,在內存中緩存過多的響應內容也會讓它付出了相應的代價。因此它推薦使用 ResponseHandler 來處理 HTTP 響應以此來避免在內存中緩存響應內容。
Document result = Request.Get("https://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);
}
}
});
最後更新:2017-05-19 13:33:36