码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient(4.3.5) - ResponseHandler

时间:2015-05-22 22:21:53      阅读:370      评论:0      收藏:0      [点我收藏+]

标签:

处理响应最简单方便的方式是实现 ResponseHandler 接口。ResponseHandler 接口包含了一个 handleResponse(HttpResponse response) 方法,此方法使用户不必再关心连接管理。当使用 ResponseHandler 的时候,HttpClient 会自动确保连接的释放无论是请求执行成功或是有异常抛出。

 

ResponseHandler 的示例

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/json");

ResponseHandler<MyJsonObject> rh = new ResponseHandler<MyJsonObject>() {

    @Override
    public JsonObject 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");
        }
        Gson gson = new GsonBuilder().create();
        ContentType contentType = ContentType.getOrDefault(entity);
        Charset charset = contentType.getCharset();
        Reader reader = new InputStreamReader(entity.getContent(), charset);
        return gson.fromJson(reader, MyJsonObject.class);
    }
};
MyJsonObject myjson = client.execute(httpget, rh);

 

HttpClient(4.3.5) - ResponseHandler

标签:

原文地址:http://www.cnblogs.com/huey/p/4523303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!