在上文中分析了 HttpURLConnection的用法,功能还是比较简单的,没有什么封装
接下来看看Apache HttpClient是如何封装httpClient的
使用的版本
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
HttpClient 5 的系统架构主要由以下几个部分组成:
GET请求代码
String resultContent = null;
String url = "http://127.0.0.1:8081/get";
HttpGet httpGet = new HttpGet(url);
//通过工厂获取
CloseableHttpClient httpClient = HttpClients.createDefault();
//请求
CloseableHttpResponse response = httpClient.execute(httpGet);
// Get status code
System.out.println(response.getVersion());
// HTTP/1.1
System.out.println(response.getCode());
// 200
System.out.println(response.getReasonPhrase());
// OK
HttpEntity entity = response.getEntity();
// Get response information
resultContent = EntityUtils.toString(entity);
System.out.println(resultContent);
创建实例
Apache HttpClient提供了一个工厂类来返回HttpClient实例
但实际上都是通过HttpClientBuilder去创建的,
Apache HttpClient通过构建者模式加上策略模式实现非常灵活的配置,以实现各种不同的业务场景
通过看build()的代码,创建HttpClient主要分为两步
public static CloseableHttpClient createDefault() {
return HttpClientBuilder.create().build();
}
第一步是初始化配置
里边很多策略模式的使用,可以实现相关的类来拓展自己的需求,可以通过HttpClient的set方法把新的策略设置进去,其他配置也可以通过RequestConfig设置好
ConnectionKeepAliveStrategy keepAliveStrategyCopy = this.keepAliveStrategy;
if (keepAliveStrategyCopy == null) {
keepAliveStrategyCopy = DefaultConnectionKeepAliveStrategy.INSTANCE;
}
AuthenticationStrategy targetAuthStrategyCopy = this.targetAuthStrategy;
if (targetAuthStrategyCopy == null) {
targetAuthStrategyCopy = DefaultAuthenticationStrategy.INSTANCE;
}
AuthenticationStrategy proxyAuthStrategyCopy = this.proxyAuthStrategy;
if (proxyAuthStrategyCopy == null) {
proxyAuthStrategyCopy = DefaultAuthenticationStrategy.INSTANCE;
}
在这里会初始化包括连接管理器、请求重试处理器、请求执行器、重定向策略、认证策略、代理、SSL/TLS等配置
第二步是创建处理器链
通过组合多个处理器来构建成处理器链处理请求

需要注意的是这里的添加顺序的方法,添加最终的执行处理器调用的是addLast()
处理器链中的每个处理器都有不同的功能,例如请求预处理、重试、身份验证、请求发送、响应解析等等。在每个处理器的处理过程中,可以对请求或响应进行修改或扩展,以满足不同的需求
最后再把初始化好的参数传递给InternalHttpClient返回一个HttpClient实例
发起请求
接下来看看请求方法
CloseableHttpResponse response = httpClient.execute(httpGet);
主要请求方法在InternalHttpClient#doExecute中
主要分为三步,第一步是将各种配置填充到上下文中HttpContext
第二步,执行刚刚封装执行链
//execChain就是上一步封装好的执行链
final ClassicHttpResponse response = this.execChain.execute(ClassicRequestBuilder.copy(request).build(), scope);
执行 execute 方法,执行链中的处理器被依次调用,每个元素都可以执行一些预处理、后处理、重试等逻辑
第三步,请求结束后,将结果转换为CloseableHttpResponse返回
接下来试试加一下自定义的拦截器和处理器
拦截器和处理器的实现是不一样的,处理器的实现是ExecChainHandler,拦截器是HttpResponseInterceptor和HttpRequestInterceptor
//执行链处理器
class MyCustomInterceptor implements ExecChainHandler {
@Override
public ClassicHttpResponse execute(ClassicHttpRequest request, ExecChain.Scope scope, ExecChain chain) throws IOException, HttpException {
System.out.println("MyCustomInterceptor-------------");
//调用下一个链
return chain.proceed(request,scope);
}
}
//响应拦截器
class MyCustomResponseInterceptor implements HttpResponseInterceptor {
@Override
public void process(HttpResponse response, EntityDetails entity, HttpContext context) throws HttpException, IOException {
System.out.println("MyCustomResponseInterceptor-------------");
}
}
//请求拦截器
class MyCustomRequestInterceptor implements HttpRequestInterceptor {
@Override
public void process(HttpRequest request, EntityDetails entity, HttpContext context) throws HttpException, IOException {
System.out.println("MyCustomRequestInterceptor-------------");
}
}
然后加入到拦截链中,custom()方法返回HttpClientBuilder来支持自定义
CloseableHttpClient httpClient = HttpClients.custom()
.addExecInterceptorLast("myCustomInterceptor", new MyCustomInterceptor())
.addRequestInterceptorFirst(new MyCustomRequestInterceptor())
.addResponseInterceptorLast(new MyCustomResponseInterceptor())
.build();
注意看日志就有输出了
拦截器和处理器都是用于拦截请求和响应的中间件,但它们在功能上有些不同:
总之,拦截器和处理器都是用于处理请求和响应的中间件,但它们的职责和功能略有不同
异步请求的HttpAsyncClient通过HttpAsyncClients工厂返回
主要的流程和同步请求差不多,包括初始化配置和初始化执行链,主要差异在执行请求那里
因为是异步执行,需要开启异步请求的执行器线程池,通过httpClient.start();方法来设置异步线程的状态,否则异步请求将无法执行
@Override
public final void start() {
if (status.compareAndSet(Status.READY, Status.RUNNING)) {
executorService.execute(ioReactor::start);
}
}
如果没有开启,会抛出异常
if (!isRunning()) {
throw new CancellationException("Request execution cancelled");
}
因为是异步请求,所以请求方法需要提供回调方法,主要实现三个方法,执行完成、失败和取消
//创建url
SimpleHttpRequest get = SimpleHttpRequest.create("GET", url);
Future<SimpleHttpResponse> future = httpClient.execute(get,
//异步回调
new FutureCallback<SimpleHttpResponse>() {
@Override
public void completed(SimpleHttpResponse result) {
System.out.println("completed---------------");
}
@Override
public void failed(Exception ex) {
System.out.println("failed---------------");
}
@Override
public void cancelled() {
System.out.println("cancelled---------------");
}
});
SimpleHttpResponse response = future.get();
通过future.get()来获取异步结果,接下来看看底层是怎么实现的
//请求
execute(SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), context, callback);
异步请求会创建SimpleRequestProducer和SimpleResponseConsumer来处理请求和响应,execute()也支持我们自己传进去
最终的请求和数据的接收都是依赖管道,过程有点像NIO
当请求时,会调用requestProducer.produce(channel);把请求数据写入channel中,在响应时,responseConsumer从channel中取得数据
源码的整一块请求代码都是通过几个匿名函数的写法完成的,看的有点绕
发起请求,匿名函数段代表的是RequestChannel的请求方法

//requestProducer的sendRequest方法
void sendRequest(RequestChannel channel, HttpContext context)
因为RequestChannel类是一个函数式接口,所以可以通过这种方式调用
public interface RequestChannel {
//请求方法也是叫sendRequest
void sendRequest(HttpRequest request, EntityDetails entityDetails, HttpContext context) throws HttpException, IOException;
}
生产和消费数据的代码都在那一刻函数段中,具体的实现细节可以看一下那一段源码,最终requestProducer也是委托RequestChannel来发起请求

消费完后通过一层一层的回调,最终到达最上边自己实现的三个方法上
异步的HttpClient也可以自定义拦截器喝处理器,实现方式和上边的一样,处理异步处理器的实现不同
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(config)
.addExecInterceptorLast("myCustomInterceptor", new MyCustomInterceptor())
.addRequestInterceptorFirst(new MyCustomRequestInterceptor())
.addResponseInterceptorLast(new MyCustomResponseInterceptor())
.build();
如果是同步的就使用HttpClients工厂,异步的使用HttpAsyncClients
//返回默认的
CloseableHttpClient httpClient = HttpClients.createDefault();
如果想实现自定义配置,可以使用HttpClients.custom()方法
基本的配置被封装在RequestConfig类中
RequestConfig config = RequestConfig.custom()
.setConnectionRequestTimeout(3L, TimeUnit.SECONDS)
.setResponseTimeout(3L, TimeUnit.SECONDS)
.setDefaultKeepAlive(10L , TimeUnit.SECONDS)
.build();
如果还不满足,可以还可以去实现这些策略类

使用自定义配置创建httpClient
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(config)
.addExecInterceptorLast("myCustomInterceptor", new MyCustomInterceptor())
.addRequestInterceptorFirst(new MyCustomRequestInterceptor())
.addResponseInterceptorLast(new MyCustomResponseInterceptor())
.build();
String url = "http://127.0.0.1:8081/get";
List<NameValuePair> nvps = new ArrayList<>();
// GET 请求参数
nvps.add(new BasicNameValuePair("username", "test"));
nvps.add(new BasicNameValuePair("password", "password"));
//将参数填充道url中
URI uri = new URIBuilder(new URI(url))
.addParameters(nvps)
.build();
//创建get请求对象
HttpGet httpGet = new HttpGet(uri);
//发起请求
CloseableHttpResponse response = httpClient.execute(httpGet);
// Get status code
System.out.println(response.getVersion()); // HTTP/1.1
System.out.println(response.getCode()); // 200
HttpEntity entity = response.getEntity();
// Get response information
String resultContent = EntityUtils.toString(entity);
System.out.println(resultContent);
这次将参数写到HttpEntity里
String url = "http://127.0.0.1:8081/post";
List<NameValuePair> nvps = new ArrayList<>();
// GET 请求参数
nvps.add(new BasicNameValuePair("username", "test"));
nvps.add(new BasicNameValuePair("password", "password"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(formEntity);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
// Get status code
System.out.println(response.getVersion()); // HTTP/1.1
System.out.println(response.getCode()); // 200
HttpEntity entity = response.getEntity();
// Get response information
String resultContent = EntityUtils.toString(entity);
System.out.println(resultContent);
和GET请求基本一致,除了用的是HttpPost,参数可以像GET一样填充到url中,也可以使用HttpEntity填充到请求体里
Json请求
String json = "{"
+ " \"username\": \"test\","
+ " \"password\": \"password\""
+ "}";
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
HttpPost post = new HttpPost("http://127.0.0.1:8081/postJson");
post.setEntity(entity);
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(post);
// Get status code
System.out.println(response.getCode()); // 200
// Get response information
String resultContent = EntityUtils.toString(response.getEntity());
System.out.println(resultContent);
和HttpURLConnection相比,做了很多封装,功能也强大了很多,例如连接池、缓存、重试机制、线程池等等,并且对于请求参数的设置更加灵活,还封装了异步请求、HTTPS等、自定义拦截器和处理器等
请求是使用了处理链的方式发起的,可以对请求和响应进行一系列处理,好处是可以将这些处理器封装成一个公共的类库,然后通过自己组合来满足自己的需求,还可以在请求和响应的不同阶段进行拦截和修改,例如添加请求头、修改请求参数、解密响应数据等,不需要在一个大类里写很多代码了,已免代码臃肿
性能方面使用了连接池技术,可以有效地复用连接,提高性能
不得不说是apache的项目,源码使用了包括构建者模式、策略模式、责任链模式等设计模式对整个httpClient进行了封装,学习到了
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po