HttpComponents で JSON レスポンスをオブジェクトに変換して取得する

チュートリアルに書いてあるとおり ResponseHandler を使うと HttpClient#execute() の返り値を特定のクラスにして返すようにできる。これを jackson を使って返すようにしてみた。

http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.html#d5e199

ResponseHandler (Apache HttpClient 4.5.2 API)

public class JacksonResponseHandler<T> implements ResponseHandler<T> {
    private static final ObjectMapper mapper = new ObjectMapper();
    private TypeReference<T> typeRef;

    @Override
    public T handleResponse(HttpResponse response) throws IOException {
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            throw new ClientProtocolException("Response contains no content");
        }
        if (!entity.getContentType().getValue().startsWith("application/json")) {
            throw new ClientProtocolException("Response is not json");
        }

        InputStream content = entity.getContent();
        if (content == null) {
            throw new ClientProtocolException("Response contains no content");
        }

        try {
            return mapper.readValue(content, typeRef);
        } catch (IOException e) {
            throw new ClientProtocolException("cannot parse as response", e);
        }
    }
}