聊聊HttpClient的ResponseHandler

2023-10-10 12:04

本文主要是介绍聊聊HttpClient的ResponseHandler,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文主要研究一下HttpClient的ResponseHandler

ResponseHandler

org/apache/http/client/ResponseHandler.java

public interface ResponseHandler<T> {/*** Processes an {@link HttpResponse} and returns some value* corresponding to that response.** @param response The response to process* @return A value determined by the response** @throws ClientProtocolException in case of an http protocol error* @throws IOException in case of a problem or the connection was aborted*/T handleResponse(HttpResponse response) throws ClientProtocolException, IOException;}

ResponseHandler定义了handleResponse方法,用于解析HttpResponse到泛型T

AbstractResponseHandler

org/apache/http/impl/client/AbstractResponseHandler.java

@Contract(threading = ThreadingBehavior.IMMUTABLE)
public abstract class AbstractResponseHandler<T> implements ResponseHandler<T> {/*** Read the entity from the response body and pass it to the entity handler* method if the response was successful (a 2xx status code). If no response* body exists, this returns null. If the response was unsuccessful (&gt;= 300* status code), throws an {@link HttpResponseException}.*/@Overridepublic T handleResponse(final HttpResponse response)throws HttpResponseException, IOException {final StatusLine statusLine = response.getStatusLine();final HttpEntity entity = response.getEntity();if (statusLine.getStatusCode() >= 300) {EntityUtils.consume(entity);throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());}return entity == null ? null : handleEntity(entity);}/*** Handle the response entity and transform it into the actual response* object.*/public abstract T handleEntity(HttpEntity entity) throws IOException;}

AbstractResponseHandler声明实现ResponseHandler接口,其handleResponse方法针对statusCode大于等于300的抛出HttpResponseException,对于entity不为null的执行handleEntity方法

BasicResponseHandler

org/apache/http/impl/client/BasicResponseHandler.java

@Contract(threading = ThreadingBehavior.IMMUTABLE)
public class BasicResponseHandler extends AbstractResponseHandler<String> {/*** Returns the entity as a body as a String.*/@Overridepublic String handleEntity(final HttpEntity entity) throws IOException {return EntityUtils.toString(entity);}@Overridepublic String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {return super.handleResponse(response);}}

BasicResponseHandler继承了AbstractResponseHandler,它将entity转为String,使用的是EntityUtils.toString(entity)方法

EntityUtils.toString

org/apache/http/util/EntityUtils.java

    public static String toString(final HttpEntity entity) throws IOException, ParseException {Args.notNull(entity, "Entity");return toString(entity, ContentType.get(entity));}private static String toString(final HttpEntity entity,final ContentType contentType) throws IOException {final InputStream inStream = entity.getContent();if (inStream == null) {return null;}try {Args.check(entity.getContentLength() <= Integer.MAX_VALUE,"HTTP entity too large to be buffered in memory");int capacity = (int)entity.getContentLength();if (capacity < 0) {capacity = DEFAULT_BUFFER_SIZE;}Charset charset = null;if (contentType != null) {charset = contentType.getCharset();if (charset == null) {final ContentType defaultContentType = ContentType.getByMimeType(contentType.getMimeType());charset = defaultContentType != null ? defaultContentType.getCharset() : null;}}if (charset == null) {charset = HTTP.DEF_CONTENT_CHARSET;}final Reader reader = new InputStreamReader(inStream, charset);final CharArrayBuffer buffer = new CharArrayBuffer(capacity);final char[] tmp = new char[1024];int l;while((l = reader.read(tmp)) != -1) {buffer.append(tmp, 0, l);}return buffer.toString();} finally {inStream.close();}}

EntityUtils.toString方法通过entity.getContent()获取InputStream,之后将InputStream读取到CharArrayBuffer,最后关闭InputStream

execute

org/apache/http/impl/client/CloseableHttpClient.java

    @Overridepublic <T> T execute(final HttpHost target, final HttpRequest request,final ResponseHandler<? extends T> responseHandler, final HttpContext context)throws IOException, ClientProtocolException {Args.notNull(responseHandler, "Response handler");final CloseableHttpResponse response = execute(target, request, context);try {final T result = responseHandler.handleResponse(response);final HttpEntity entity = response.getEntity();EntityUtils.consume(entity);return result;} catch (final ClientProtocolException t) {// Try to salvage the underlying connection in case of a protocol exceptionfinal HttpEntity entity = response.getEntity();try {EntityUtils.consume(entity);} catch (final Exception t2) {// Log this exception. The original exception is more// important and will be thrown to the caller.this.log.warn("Error consuming content after an exception.", t2);}throw t;} finally {response.close();}}

CloseableHttpClient的execute方法先执行execute,然后try catch执行responseHandler.handleResponse,然后执行EntityUtils.consume(entity),在ClientProtocolException的时候也会执行EntityUtils.consume(entity),最后执行response.close()

小结

HttpClient提供了ResponseHandler接口,它有一个实现类是BasicResponseHandler,将entity的content转为string;相应的CloseableHttpClient也提供了支持ResponseHandler参数的execute方法,它先执行无handler的execute方法,然后try catch执行responseHandler.handleResponse,然后执行EntityUtils.consume(entity),在ClientProtocolException的时候也会执行EntityUtils.consume(entity),最后执行response.close()。

这篇关于聊聊HttpClient的ResponseHandler的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/180312

相关文章

C#使用HttpClient进行Post请求出现超时问题的解决及优化

《C#使用HttpClient进行Post请求出现超时问题的解决及优化》最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也... 目录优化结论单例HttpClient连接池耗尽和并发并发异步最终优化后优化结论我直接上优化结论吧,

Apache HttpClient使用详解

转载地址:http://eksliang.iteye.com/blog/2191017 Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟

聊聊说话的习惯

1 在日常生活中,每个人都有固定的说话习惯。心理学研究表明,通过一个人的说话习惯,也可以分析出他的性格特点。对于每一个人来讲,说话习惯已经融为他们生活中的一部分。在社交活动中,一些不良的说话习惯很可能会给他们带来麻烦。因此,了解说话习惯对心理活动的影响是十分有必要的。 2 具有顺畅的说话习惯的人,大多思路清晰、语速适中、用词准确并且声声人耳,是典型的顺畅型说话方式这种类型的人要么不说话,要么

项目一(一) HttpClient中的POST请求和GET请求

HttpClient中的POST请求和GET请求 一、HttpClient简述 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLU

聊聊分布式,再讨论分布式解决方案

前言 最近很久没有写博客了,一方面是因为公司事情最近比较忙,另外一方面是因为在进行 CAP 的下一阶段的开发工作,不过目前已经告一段落了。 接下来还是开始我们今天的话题,说说分布式事务,或者说是我眼中的分布式事务,因为每个人可能对其的理解都不一样。 分布式事务是企业集成中的一个技术难点,也是每一个分布式系统架构中都会涉及到的一个东西,特别是在微服务架构中,几乎可以说是无法避免,本文就分布式事

HttpClient的快速入门使用

目录 一、介绍 二、Get方式请求发送入门案例  实现步骤:  测试结果: 三、Post方式请求发送入门案例  实现步骤: 测试结果: 一、介绍 HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。 HttpCl

聊聊资源调度

资源调度 般分为两个阶段: 是实现物理资源的虚拟化(即资源的抽象)于当前机器的性能越来越好,硬件配置越来越高,直接用物理机跑业务比较浪费,所以将物理机分割成更小单位的虚拟机,这样可以显著提升机器的利用效率,在公司内部一般采用容器技术来隔离资源 是将资源虚拟化后进 步在时间和空间上实现更细粒度的编排 ,优化资源的使用。 1 .一些数据 如果公司的几万台机器都是物理机,那么资源的使用率稍低: CP

聊聊Spark中的宽依赖和窄依赖

开门见山,本文就针对一个点,谈谈Spark中的宽依赖和窄依赖,这是Spark计算引擎划分Stage的根源所在,遇到宽依赖,则划分为多个stage,针对每个Stage,提交一个TaskSet: 上图:一张网上的图: 基于此图,分析下这里为什么前面的流程都是窄依赖,而后面的却是宽依赖: 我们仔细看看,map和filter算子中,对于父RDD来说,一个分区内的数据,有且仅有一个子RDD的分区来

聊聊灰度发布

有没有在北京面试java的小伙伴,每家公司面试问的问题都不一样,昨天面试官问到了灰度发布,一脸懵,好像在哪儿听说过,毕竟我都没发布过,之前都是项目组长在干这些事儿,所以聊聊,了解一下 什么是灰度发布 全量发布:把旧服务kill掉,把新服务启动,这个过程就可以理解为全量发布 回滚周期长 如果我们更新完应用之后,我们做线上回归测试的时候发现有BUG,这个时候就要做回滚,过程就是把新服

httpclient支持socks5和http代理调用接口

httpclient支持socks5和http代理调用接口 package com.ruoyi.web.controller.util;import org.apache.http.HttpHost;import org.apache.http.NameValuePair;import org.apache.http.auth.AuthScope;import org.apa