相比于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学习的更多相关文章

  1. 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移

    不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.superviso ...

  2. EF 学习系列二 数据库表的创建和表关系配置(Fluent API、Data Annotations、约定)

    上一篇写了<Entity Farmework领域建模方式 3种编程方式>,现在就Code First 继续学习 1.数据库表的创建 新建一个MVC的项目,在引用右击管理NuGet程序包,点 ...

  3. EF Code-First 学习之旅 Fluent API

    Mappings To Database Model-wide Mapping Set default Schema Set Custom Convetions Entity Mapping To S ...

  4. EF Code First 学习笔记:约定配置 Data Annotations+Fluent API

    要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...

  5. 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...

  6. EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射

    I.EF里的默认映射 上篇文章演示的通过定义实体类就可以自动生成数据库,并且EF自动设置了数据库的主键.外键以及表名和字段的类型等,这就是EF里的默认映射.具体分为: 数据库映射:Code First ...

  7. 8.2 使用Fluent API进行实体映射【Code-First系列】

    现在,我们来学习怎么使用Fluent API来配置实体. 一.配置默认的数据表Schema Student实体 using System; using System.Collections.Gener ...

  8. 8.3 使用Fluent API进行属性映射【Code-First系列】

    现在,我打算学习,怎么用Fluent API来配置领域类中的属性. using System; using System.Collections.Generic; using System.Linq; ...

  9. 8.Fluent API in Code-First【Code-First系列】

    在前面的章节中,我们已经看到了各种不同的数据注解特性.现在我们来学习一下Fluent API. Fluent API是另外一种配置领域类的方式,它提供了更多的配置相比数据注解特性. Mappings[ ...

随机推荐

  1. 【转】解决memcached启动失败

    原文:http://chenzhou123520.iteye.com/blog/1925196 linux上启动Memcache报错: 原因一般有两个, 一个是操作系统里确实没有包含该共享库(lib* ...

  2. 学习RocketMQ (一) 安装并且启动MQ

    1.使用RocketMQ 的 软件要求 64bit OS, Linux/Unix/Mac is recommended;64bit JDK 1.8+;Maven 3.2.xGit 1)安装Linux ...

  3. js 切换全屏

    公司有一个需求就是点击某一个按钮实现全屏切换功能,然后呢我就在网上扒了段代码.封装了一下.使用的小伙伴们可以看看哦! 切换全屏代码 <!DOCTYPE html> <html> ...

  4. C#.Net调用VB.Net中的MY

    用过VB.NET的人应该只要MY有多强大了吧,是不是很想在C#中也能调用呢? 当然是可以的,.net作为微软的跨语言的平台,必须是能实现的,不然微软就自己打自己嘴巴了~ 回到正题上: 1.在程序中加上 ...

  5. 给GridControl中的某列添加图片

    要让GridControl的某列显示图片只需要数据源中有图片就可以正确显示 1.给DataSet添加一列,格式为image ds.Tables[].Columns.Add("SIGN&quo ...

  6. 使用JavaScript生成二维码教程-附qrcodejs中文文档

    使用javascript生成二维码 依赖jquery 需要使用到的库 https://github.com/davidshimjs/qrcodejs DIV <div id="qrco ...

  7. iOS学习——如何在mac上获取开发使用的模拟器的资源以及模拟器中每个应用的应用沙盒

    如题,本文主要研究如何在mac上获取开发使用的模拟器的资源以及模拟器中每个应用的应用沙盒.做过安卓开发的小伙伴肯定很方便就能像打开资源管理器一样查看我们写到手机本地或应用中的各种资源,但是在iOS开发 ...

  8. RecyclerView 加入一个滑动控件bug处理 GridView只显示第一行

    如果RecyclerView 多样式布局,比如要加入一个展示多个图看的需求.自然想到用gridview给嵌套一下. 想法当然是可以的,但是发现,嵌套出来的效果是,gridview只显示一行. 想想原因 ...

  9. spring boot 错误,求大神帮解决

    Exception in thread "main" java.lang.IllegalStateException: Failed to read Class-Path attr ...

  10. 苹果快速的修复了Mac OS High Sierra 上出现了root的漏洞

    最近苹果因为Mac最新系统 Mac OS High Sierra 上出现了root的漏洞走上了风口浪尖,不过还好,在一封苹果给科技媒体'9to5 Mac'的回复中得知,苹果在接收到报告之后,立即展开修 ...