最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

深入了解HttpClient的ResponseHandler接口

 更新時(shí)間:2023年10月10日 08:31:03   作者:codecraft  
這篇文章主要為大家介紹了深入了解HttpClient的ResponseHandler接口,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

本文主要研究一下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聲明實(shí)現(xiàn)ResponseHandler接口,其handleResponse方法針對(duì)statusCode大于等于300的拋出HttpResponseException,對(duì)于entity不為null的執(zhí)行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轉(zhuǎn)為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方法通過(guò)entity.getContent()獲取InputStream,之后將InputStream讀取到CharArrayBuffer,最后關(guān)閉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方法先執(zhí)行execute,然后try catch執(zhí)行responseHandler.handleResponse,然后執(zhí)行EntityUtils.consume(entity),在ClientProtocolException的時(shí)候也會(huì)執(zhí)行EntityUtils.consume(entity),最后執(zhí)行response.close()

小結(jié)

HttpClient提供了ResponseHandler接口,它有一個(gè)實(shí)現(xiàn)類是BasicResponseHandler,將entity的content轉(zhuǎn)為string;相應(yīng)的CloseableHttpClient也提供了支持ResponseHandler參數(shù)的execute方法,它先執(zhí)行無(wú)handler的execute方法,然后try catch執(zhí)行responseHandler.handleResponse,然后執(zhí)行EntityUtils.consume(entity),在ClientProtocolException的時(shí)候也會(huì)執(zhí)行EntityUtils.consume(entity),最后執(zhí)行response.close()。

以上就是HttpClient的ResponseHandler的詳細(xì)內(nèi)容,更多關(guān)于HttpClient ResponseHandler的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • java中switch case語(yǔ)句需要加入break的原因解析

    java中switch case語(yǔ)句需要加入break的原因解析

    這篇文章主要介紹了java中switch case語(yǔ)句需要加入break的原因解析的相關(guān)資料,需要的朋友可以參考下
    2017-07-07
  • 一名Java高級(jí)工程師需要學(xué)什么?

    一名Java高級(jí)工程師需要學(xué)什么?

    作為一名Java高級(jí)工程師需要學(xué)什么?如何成為一名合格的工程師,這篇文章給了你較為詳細(xì)的答案,需要的朋友可以參考下
    2017-08-08
  • 淺談SpringBoot2.3 新特配置文件屬性跟蹤

    淺談SpringBoot2.3 新特配置文件屬性跟蹤

    這篇文章主要介紹了淺談SpringBoot2.3 新特配置文件屬性跟蹤,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • Java服務(wù)器主機(jī)信息監(jiān)控工具類的示例代碼

    Java服務(wù)器主機(jī)信息監(jiān)控工具類的示例代碼

    這篇文章主要介紹了Java服務(wù)器主機(jī)信息監(jiān)控工具類的示例代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-04-04
  • Java創(chuàng)建非阻塞的HTTP服務(wù)器的實(shí)現(xiàn)

    Java創(chuàng)建非阻塞的HTTP服務(wù)器的實(shí)現(xiàn)

    本文主要介紹了Java創(chuàng)建非阻塞的HTTP服務(wù)器的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-04-04
  • gataway斷言工作流程源碼剖析

    gataway斷言工作流程源碼剖析

    這篇文章主要為大家介紹了gataway斷言工作流程源碼剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • 在SpringBoot框架下實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出的方法詳解

    在SpringBoot框架下實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出的方法詳解

    SpringBoot是由Pivotal團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來(lái)簡(jiǎn)化新Spring應(yīng)用的初始搭建以及開(kāi)發(fā)過(guò)程,今天我們就使用純前對(duì)按表格控件帶大家了解,如何在Spring Boot框架下實(shí)現(xiàn)Excel服務(wù)端導(dǎo)入導(dǎo)出,需要的朋友可以參考下
    2023-06-06
  • 解讀Spring框架中常用的設(shè)計(jì)模式

    解讀Spring框架中常用的設(shè)計(jì)模式

    這篇文章主要介紹了解讀Spring框架中常用的設(shè)計(jì)模式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • springboot集成easypoi導(dǎo)出word換行處理過(guò)程

    springboot集成easypoi導(dǎo)出word換行處理過(guò)程

    Spring?Boot集成Easypoi導(dǎo)出Word時(shí),換行符\n失效顯示為空格,解決方法包括生成段落或替換模板中\(zhòng)n為回車,同時(shí)需確保變量{{temp}}在Map中設(shè)為"??"(帶空格空字符串),避免空指針或殘留變量
    2025-08-08
  • spring-redis-session 自定義 key 和過(guò)期時(shí)間

    spring-redis-session 自定義 key 和過(guò)期時(shí)間

    這篇文章主要介紹了spring-redis-session 自定義 key 和過(guò)期時(shí)間,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12

最新評(píng)論

台江县| 安顺市| 淮北市| 洛隆县| 荔浦县| 庆元县| 沾化县| 靖远县| 长治市| 新干县| 祥云县| 揭西县| 秦皇岛市| 剑川县| 新邵县| 霍山县| 额尔古纳市| 分宜县| 舞阳县| 东城区| 历史| 承德市| 都安| 尼勒克县| 江永县| 库伦旗| 英德市| 昌平区| 洪湖市| 安图县| 德庆县| 澎湖县| 桦南县| 琼海市| 玉树县| 萝北县| 新安县| 北安市| 高青县| 封丘县| 新田县|