HttpClient4.2 Fluent API学习
相比于HttpClient 之前的版本号,HttpClient 4.2 提供了一组基于流接口(fluent interface)概念的更易使用的API,即Fluent API.
为了方便使用,Fluent API仅仅暴露了一些最主要的HttpClient功能。
这样,Fluent API就将开发人员从连接管理、资源释放等繁杂的操作中解放出来,从而更易进行一些HttpClient的简单操作。
(原文地址:http://blog.csdn.net/vector_yi/article/details/24298629转载请注明出处)
还是利用详细样例来说明吧。
下面是几个使用Fluent API的代码例子:
一、最主要的http请求功能
运行Get、Post请求,不正确返回的响应作处理
package com.vectoryi.fluent; import java.io.File; import org.apache.http.HttpHost;
import org.apache.http.HttpVersion;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType; public class FluentRequests { public static void main(String[] args)throws Exception {
//运行一个GET请求,同一时候设置Timeout參数并将响应内容作为String返回
Request.Get("http://blog.csdn.net/vector_yi")
.connectTimeout(1000)
.socketTimeout(1000)
.execute().returnContent().asString(); //以Http/1.1版本号协议运行一个POST请求,同一时候配置Expect-continue handshake达到性能调优,
//请求中包括String类型的请求体并将响应内容作为byte[]返回
Request.Post("http://blog.csdn.net/vector_yi")
.useExpectContinue()
.version(HttpVersion.HTTP_1_1)
.bodyString("Important stuff", ContentType.DEFAULT_TEXT)
.execute().returnContent().asBytes(); //通过代理运行一个POST请求并加入一个自己定义的头部属性,请求包括一个HTML表单类型的请求体
//将返回的响应内容存入文件
Request.Post("http://blog.csdn.net/vector_yi")
.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"));
} }
二、在后台线程中异步运行多个请求
package com.vectoryi.fluent; import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; import org.apache.http.client.fluent.Async;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.concurrent.FutureCallback; public class FluentAsync { public static void main(String[] args)throws Exception {
// 利用线程池
ExecutorService threadpool = Executors.newFixedThreadPool(2);
Async async = Async.newInstance().use(threadpool); Request[] requests = new Request[] {
Request.Get("http://www.google.com/"),
Request.Get("http://www.yahoo.com/"),
Request.Get("http://www.apache.com/"),
Request.Get("http://www.apple.com/")
}; Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
// 异步运行GET请求
for (final Request request: requests) {
Future<Content> future = async.execute(request, new FutureCallback<Content>() { public void failed(final Exception ex) {
System.out.println(ex.getMessage() + ": " + request);
} public void completed(final Content content) {
System.out.println("Request completed: " + request);
} public void cancelled() {
} });
queue.add(future);
} while(!queue.isEmpty()) {
Future<Content> future = queue.remove();
try {
future.get();
} catch (ExecutionException ex) {
}
}
System.out.println("Done");
threadpool.shutdown();
} }
三、更高速地启动请求
package com.vectoryi.fluent; import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request; public class FluentQuickStart { public static void main(String[] args) throws Exception { Request.Get("http://targethost/homepage")
.execute().returnContent();
Request.Post("http://targethost/login")
.bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
.execute().returnContent();
}
}
四、处理Response
在本例中是利用xmlparsers来解析返回的ContentType.APPLICATION_XML类型的内容。
package com.vectoryi.fluent; import java.io.IOException;
import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.w3c.dom.Document;
import org.xml.sax.SAXException; public class FluentResponseHandling { public static void main(String[] args)throws Exception {
Document result = Request.Get("http://www.baidu.com")
.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);
}
Charset charset = contentType.getCharset();
if (charset == null) {
charset = Consts.ISO_8859_1;
}
return docBuilder.parse(entity.getContent(), charset.name());
} catch (ParserConfigurationException ex) {
throw new IllegalStateException(ex);
} catch (SAXException ex) {
throw new ClientProtocolException("Malformed XML document", ex);
}
} });
// 处理得到的result
System.out.println(result);
} }
HttpClient4.2 Fluent API学习的更多相关文章
- 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移
不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.superviso ...
- EF 学习系列二 数据库表的创建和表关系配置(Fluent API、Data Annotations、约定)
上一篇写了<Entity Farmework领域建模方式 3种编程方式>,现在就Code First 继续学习 1.数据库表的创建 新建一个MVC的项目,在引用右击管理NuGet程序包,点 ...
- EF Code-First 学习之旅 Fluent API
Mappings To Database Model-wide Mapping Set default Schema Set Custom Convetions Entity Mapping To S ...
- EF Code First 学习笔记:约定配置 Data Annotations+Fluent API
要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...
- 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...
- EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射
I.EF里的默认映射 上篇文章演示的通过定义实体类就可以自动生成数据库,并且EF自动设置了数据库的主键.外键以及表名和字段的类型等,这就是EF里的默认映射.具体分为: 数据库映射:Code First ...
- 8.2 使用Fluent API进行实体映射【Code-First系列】
现在,我们来学习怎么使用Fluent API来配置实体. 一.配置默认的数据表Schema Student实体 using System; using System.Collections.Gener ...
- 8.3 使用Fluent API进行属性映射【Code-First系列】
现在,我打算学习,怎么用Fluent API来配置领域类中的属性. using System; using System.Collections.Generic; using System.Linq; ...
- 8.Fluent API in Code-First【Code-First系列】
在前面的章节中,我们已经看到了各种不同的数据注解特性.现在我们来学习一下Fluent API. Fluent API是另外一种配置领域类的方式,它提供了更多的配置相比数据注解特性. Mappings[ ...
随机推荐
- 小议webpack下的AOP式无侵入注入
说起来, 面向切面编程(AOP)自从诞生之日起,一直都是计算机科学领域十分热门的话题,但是很奇怪的是,在前端圈子里,探讨AOP的文章似乎并不是多,而且多数拘泥在给出理论,然后实现个片段的定式)难免陷入 ...
- DbContext 中的 Explicit interface implementation
疑惑 前段时间一直再用Entity Framework 6,写了一些公用的方法,在这个过程中发现了DbContext实现的接口IObjectContextAdapter,可以通过这个接口访问到更底层的 ...
- Layui框架+PHP打造个人简易版网盘系统
网盘系统 大家应该都会注册过致命的一些网盘~如百度云.百科介绍:网盘,又称网络U盘.网络硬盘,是由互联网公司推出的在线存储服务,服务器机房为用户划分一定的磁盘空间,为用户免费或收费提供文件的存储. ...
- 简单聊聊java中如何判定一个对象可回收
背景 说到java的特性,其中一个最重要的特性便是java通过new在堆中分配给对象的内存,不需要程序员主动去释放,而是由java虚拟机自动的回收.这也是java和C++的主要区别之一:那么虚拟机是如 ...
- 逆向知识第八讲,if语句在汇编中表达的方式
逆向知识第八讲,if语句在汇编中表达的方式 一丶if else的最简单情况还原(无分支情况) 高级代码: #include "stdafx.h" int main(int argc ...
- wkt转换geojson
应用配置 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.o ...
- WPF 完美截图 <二>
根据WPF 完美截图 <一>总结: 1.BitmapSource与BitmapImage及CorppedBitmap之间的转换 2.中心及边角的模板实现及其拖动 3.除了拖动矩形外区域要实 ...
- RabbitMQ之路由
为了实现一个新功能:只订阅消息的一个子集,例如只需要把严重的错误日志信息写入日志文件(存储到磁盘上),但同时仍然把所有的日志信息输出到控制台中. 绑定(Bindings) 创建绑定 channel.q ...
- spring aop使用
最近做一个数据库分离的功能,其中用到了spring aop,主要思路就是在service层的方法执行前根据注解(当然也可以根据方法名称,如果方法名称写的比较统一的话)来判断具体使用哪个库.所以想着再回 ...
- Kaggle实战之二分类问题
0. 前言 1. MNIST 数据集 2. 二分类器 3. 效果评测 4. 多分类器与误差分析 5. Kaggle 实战 0. 前言 "尽管新技术新算法层出不穷,但是掌握好基础算法就能解决手 ...