HttpClient(4.3.5) - ResponseHandler

处理响应最简单方便的方式是实现 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)