Apache HttpClient 4 Custom Bytes ResponseHandler

An interesting thing I needed was to retrieve an image from a URL. HttpClient provides a BasicResponseHandler, which returns a String. I needed bytes in order to accomplish this, I had to implement my own response handler.

    /**
     * Get the weather radar bytes image.
     * @return byte[] of weather radar data
     */
    @Nullable
    public byte[] getWeatherRadarBytes() {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://services.intellicast.com/200904-01/387694749/Image/Radar/Winter%20Storm%20Mosaic/Loop/SectorName/bwg");

        ResponseHandler<byte[]> responseHandler = new ResponseHandler<byte[]>() {
            @Nullable
            public byte[] handleResponse(
                HttpResponse response) throws IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };

        byte[] responseBody = null;
        try {
            responseBody = httpClient.execute(httpGet, responseHandler);
        } catch (IOException e) {
            log.error("IOException", e);
            //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();
        }
        return responseBody;
    }
This entry was posted in Java and tagged , , , , , . Bookmark the permalink.

1 Response to Apache HttpClient 4 Custom Bytes ResponseHandler

  1. Pingback: Java Ninja Chronicles By Norris Shelton, Jr

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s