【问题标题】:apache httpclient- most efficient way to read responseapache httpclient-读取响应的最有效方法
【发布时间】:2013-07-04 07:28:11
【问题描述】:

我正在为 httpclient 使用 apache httpcompnonents 库。我想在多线程应用程序中使用它,在该应用程序中,线程数会非常高,并且会有频繁的 http 调用。这是我用来在执行调用后读取响应的代码。

HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);

我只是想确认这是阅读回复的最有效方式吗?

谢谢, 赫曼特

【问题讨论】:

    标签: apache-httpclient-4.x


    【解决方案1】:

    这实际上代表了处理 HTTP 响应的最低效方式。

    您很可能希望将响应的内容消化成某种领域对象。那么,以字符串的形式在内存中缓冲它有什么意义呢?

    处理响应处理的推荐方法是使用自定义ResponseHandler,它可以通过直接从底层连接流式传输内容来处理内容。使用ResponseHandler 的额外好处是,它完全无需处理连接释放和资源释放。

    编辑:修改示例代码以使用 JSON

    这是一个使用 HttpClient 4.2 和 Jackson JSON 处理器的示例。 Stuff 被假定为带有 JSON 绑定的域对象。

    ResponseHandler<Stuff> rh = new ResponseHandler<Stuff>() {
    
        @Override
        public Stuff 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");
            }
            JsonFactory jsonf = new JsonFactory();
            InputStream instream = entity.getContent();
            // try - finally is not strictly necessary here 
            // but is a good practice
            try {
                JsonParser jsonParser = jsonf.createParser(instream);
                // Use the parser to deserialize the object from the content stream
                return stuff;
            }  finally {
                instream.close();
            }
        }
    };
    DefaultHttpClient client = new DefaultHttpClient();
    Stuff mystuff = client.execute(new HttpGet("http://somehost/stuff"), rh);
    

    【讨论】:

    • 感谢 oleg,听取您的建议,我现在使用了 responsehandler。但是我需要响应字符串来遍历结果,使用 EntityUtils.toString(entity); 是否有效? with 在响应处理程序中?
    • @Hemant:您错过了我试图了解的最重要的一点:将 HTTP 消息内容转换为字符串是低效,无论您如何操作。
    • 我的担心成真了...但是我需要将此字符串转换为 jsonObject,因为此服务返回 json 字符串...现在如何在不将其转换为字符串的情况下转换为 jsonobject?跨度>
    • @Hemant:HttpClient 与内容无关。你可以使用任何你想要的解析器。我将答案更改为使用 Jackson JSON 处理器。希望这会有所帮助。
    • 对于错误处理,什么类会捕获你在代码中抛出的那些异常?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多