《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("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<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);
}
}
});
相关文章
|
4月前
|
API
el-autocomplete那些在饿了么官方文档看不到的API
el-autocomplete那些在饿了么官方文档看不到的API
|
6月前
|
XML Java API
该丢弃 HttpClient 了,这款轻量级 HTTP 客户端 API 框架很强
一般情况下是后端提供接口,前端调用,解决需求,但是有的时候为了方便,复用别人的接口(网上的,公共的第三方接口(短信、天气等)),就出现了后端调用后端接口的情况。 此外,因为业务关系,要和许多不同第三方公司进行对接。这些服务商都提供基于http的api,但是每家公司提供api具体细节差别很大。
|
6月前
|
前端开发 API
Angular HTTPClient API 在 SAP 电商云中的使用
Angular HTTPClient API 在 SAP 电商云中的使用
39 0
|
JavaScript 前端开发 定位技术
ArcGIS API For JavaScript官方文档(六)之设置范围
ArcGIS API For JavaScript官方文档(六)之设置范围
|
存储 JSON 前端开发
ArcGIS API For JavaScript官方文档(一)之默认API配置
ArcGIS API For JavaScript官方文档(一)之默认API配置
|
开发框架 前端开发 JavaScript
.NET Core Web API使用HttpClient提交文件的二进制流(multipart/form-data内容类型)
.NET Core Web API使用HttpClient提交文件的二进制流(multipart/form-data内容类型)
333 0
.NET Core Web API使用HttpClient提交文件的二进制流(multipart/form-data内容类型)
|
机器学习/深度学习 关系型数据库 API
DB表的关系及EF中Fluent API的使用
DB表的关系及EF中Fluent API的使用
103 0
DB表的关系及EF中Fluent API的使用
|
Web App开发 前端开发 .NET
ASP.NET MVC Web API 学习笔记----HttpClient简介
  1. HttpClient简单介绍  依稀还记得那个时候用WebClient,HttpWebRequest来发送一个请求,现在ASP.NET MVC4中自带了一个类HttpClient,用于接收HttpResponseMessage和发送HttpRequestMesssage。
1379 0
|
Web App开发 JSON 前端开发

热门文章

最新文章