5.1.Easy to use facade API
HttpClient從4.2開始支持快速api。快速api僅僅實現了HttpClient的基本功能,它只要用於一些不需要靈活性的簡單場景。例如,快速api不需要用戶處理連接管理和資源釋放。
下面是幾個使用快速api的例子:
// 執行一個get方法,設置超時時間,並且將結果變成字符串
Request.Get("http://www.yeetrack.com/")
.connectTimeout(1000)
.socketTimeout(1000)
.execute().returnContent().asString();
// 使用HTTP/1.1,通過'expect-continue' handshake來執行post方法
// 內容包含一個字符串,並且將結果轉化成byte數組
Request.Post("http://www.yeetrack.com/do-stuff")
.useExpectContinue()
.version(HttpVersion.HTTP_1_1)
.bodyString("Important stuff", ContentType.DEFAULT_TEXT)
.execute().returnContent().asBytes();
// 通過代理服務器來執行一個帶有特殊header的post請求,post請求中帶有form表單,並且將返回結果寫入文件
Request.Post("http://www.yeetrack.com/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"));
如果需要在指定的安全上下文中執行某些請求,我們也可以直接使用Exector,這時候用戶的認證信息就會被緩存起來,以便後續的請求使用。
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();
5.1.1.響應處理
一般情況下,HttpClient的快速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);
}
}
});