深入了解HttpClient的ResponseHandler接口

 更新时间:2023年10月10日 08:31:03   作者:codecraft  
这篇文章主要为大家介绍了深入了解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 (>= 300
     * status code), throws an {@link HttpResponseException}.
     */
    @Override
    public 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.
     */
    @Override
    public String handleEntity(final HttpEntity entity) throws IOException {
        return EntityUtils.toString(entity);
    }
    @Override
    public 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

@Override
    public <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 exception
            final 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的详细内容,更多关于HttpClient ResponseHandler的资料请关注脚本之家其它相关文章!

相关文章

  • SpringBoot实现滑块验证码验证登陆校验功能详解

    SpringBoot实现滑块验证码验证登陆校验功能详解

    验证码作为一种自然人的机器人的判别工具,被广泛的用于各种防止程序做自动化的场景中。传统的字符型验证安全性已经名存实亡的情况下,各种新型的验证码如雨后春笋般涌现,今天给大家分享一篇SpringBoot实现滑块验证码
    2022-09-09
  • Java动态代理机制的实例详解

    Java动态代理机制的实例详解

    这篇文章主要介绍了 Java动态代理机制的实例详解的相关资料,希望通过本文大家能够掌握动态代理机制,需要的朋友可以参考下
    2017-09-09
  • Java之Pattern.compile函数用法详解

    Java之Pattern.compile函数用法详解

    这篇文章主要介绍了Java之Pattern.compile函数用法详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • Java输出多位小数的三种方法(附代码)

    Java输出多位小数的三种方法(附代码)

    这篇文章主要给大家介绍了关于Java输出多位小数的三种方法的相关资料,在实际工作中常常需要设定数字的输出格式,如以百分比的形式输出,或者设定小数位数等,需要的朋友可以参考下
    2023-07-07
  • Spring Boot深入学习数据访问之Spring Data JPA与Hibernate的应用

    Spring Boot深入学习数据访问之Spring Data JPA与Hibernate的应用

    Spring Data JPA是Spring Data的子项目,在使用Spring Data JPA之前,先了解一下Hibernate,因为Spring Data JPA是由Hibernate默认实现的
    2022-10-10
  • SpringBoot整合EasyCaptcha实现图形验证码功能

    SpringBoot整合EasyCaptcha实现图形验证码功能

    这篇文章主要介绍了SpringBoot整合EasyCaptcha实现图形验证码功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2024-02-02
  • java泛型学习示例

    java泛型学习示例

    Java泛型(Generics)是JDK5开始引入的一个新特性,允许在定义类和接口的时候使用类型参数(Type Parameter)。下面是学习泛型的示例
    2014-04-04
  • SpringBoot文件上传同时接收复杂参数的过程详解

    SpringBoot文件上传同时接收复杂参数的过程详解

    这篇文章主要介绍了SpringBoot文件上传同时,接收复杂参数,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-12-12
  • SpringBoot使用Swagger生成多模块的API文档

    SpringBoot使用Swagger生成多模块的API文档

    这篇文章将以 Spring Boot 多模块项目为例,为大家详细介绍一下如何使用 Swagger 生成多模块的 API 文档,感兴趣的小伙伴可以了解一下
    2025-02-02
  • spring配置定时任务的几种方式总结

    spring配置定时任务的几种方式总结

    这篇文章主要介绍了spring配置定时任务的几种方式总结,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12

最新评论