java fluent api_《HttpClient 官方文档》第五章 Fluent API

本文档介绍了HttpClient 4.2版本引入的流式API,提供了一种简单易用的接口,用于执行HTTP请求。示例包括GET、POST请求的设置,如超时、期望继续握手、自定义头部、代理以及安全认证。强调了使用ResponseHandler处理HTTP响应以避免内存中缓存大量内容的重要性。
摘要由CSDN通过智能技术生成

原文链接  译者[white]

第五章:流式 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("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();

5.1.1. 响应处理

流式接口(Fluent API) 增加了使用者对连接的管理和资源的分配上的便利性。在许多场景下,在内存中缓存过多的响应内容也会让它付出了相应的代价。因此它推荐使用 ResponseHandler 来处理 HTTP 响应以此来避免在内存中缓存响应内容。

Document result = Request.Get("http://somehost/content")

.execute().handleResponse(new ResponseHandler() {

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);

}

}

});

d0c1501a6d8bb921cf36400dc89de69f.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值