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;
    }
Advertisements
Posted in Java | Tagged , , , , , | 1 Comment

Apache HttpClient 4 JSON post example with a generic method

In a previous post HttpClient 4 Json Post I showed how to post a Json object to a URL. That was useful, but required writing a method for each type of object you needed posted. A cleaner way is to use Java Generics to make a method that can accept multiple types of objects and can even return specific objects instead of a Json string.

    /**
     * Returns the http response as the specified object.
     * @param url the url to request
     * @param object the object to convert to the json payload
     * @param responseType the object type to convert the json response into
     * @throws IOException
     */
    public static <T> T postForObject(String url, Object object, Class<T> responseType) throws IOException {
        log.debug("Post: " + url);
        String response = "";
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(JsonUtils.toJson(object));
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-type", "application/json");
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            response = httpclient.execute(httpPost, responseHandler);
        } catch (IOException e) {
            log.error("IOException from " + url + " with " + object , e);
            throw e;
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return JsonUtils.toObject(response, responseType);
    }

The method return type is modified to return <T> T and the method signature is changed to include Class<T> responseType. Then responseType is used to tell the Json library what type of object is desired.

Here is a simple usage of the post method.

            AccountResponse accountResponse =
                    HttpUtils.postForObject(Server.IGP_ADAPTER_URL + "/accountBalances",
                            accountRequest,
                            AccountResponse.class);
Posted in Java | Tagged , , , , , , , | Leave a comment

Apache HttpClient 4 JSON post example

Posting JSON to a URL is a common use case. Here is a follow-on to HttpClient Post for a String.

    /**
     * Performs HTTP post.
     * @param url http resource to post
     * @return string response
     */
    protected String post(String url, MyJsonObject myJsonObject) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(JsonUtils.toJson(myJsonObject));
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-type", "application/json");
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            response = httpclient.execute(httpPost, responseHandler);
        } catch (IOException e) {
            log.error("IOException from " + url + " with " + object , e);
            throw e;
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return responseBody;
    }

Line 13 and 14 convert the object to be posted into a Json string and set it as the payload to be sent to the URL.
Line 15 sets the content type so the URL knows that you can accept JSON as a response.

Posted in Java | Tagged , , , , | 1 Comment

Apache HttpClient 4 String post example

Continuing from my Http Get Example, here is an example of an HttpClient4 String post example.

    /**
     * Performs HTTP post.
     * @param url http resource to post
     * @return string response
     */
    protected String post(String url) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = null;
        try {
            responseBody = httpClient.execute(httpPost, responseHandler);
        } catch (IOException e) {
            log.error("IOException", e);
        } 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;
    }
Posted in Java | Tagged , , , , , , , , | 1 Comment

Apache HttpClient 4 String get example

This was an older piece of code that I had. Add the following dependency.

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.0.1</version>
        </dependency>

I made a wrapper method that performs a get of a given URL and returns a string.

    /**
     * Performs HTTP gets.
     * @param url http resource to get
     * @return string response
     */
    protected String get(String url) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = null;
        try {
            responseBody = httpClient.execute(httpGet, responseHandler);
        } catch (IOException e) {
            log.error("IOException", e);
        } 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;
    }
Posted in Java | Tagged , , , , | 1 Comment

Maven system scope

Every once in a while, you have a library that isn’t in a repository and shouldn’t be there for some reason. We had such a library. How do you use that library when it is on your local system instead of in a repository? Use the system scope.

<dependency>
      <groupId>com.this.and.that</groupId>
      <artifactId>non-repo-library</artifactId>
      <version>1.0</version>
      <scope>system</scope>
      <systemPath>/my/path/to/lib.jar</systemPath>
    </dependency>

System scope tells Maven that the dependency is on the file system. System Path tells Maven where to find the dependency.

Posted in Maven | Tagged , , , , | Leave a comment

Spring P-notation

Spring P-notation was made to make creating spring config files a little neater and shorter. Here is what a typical file would look like.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc.xsd
                           http://www.springframework.org/schema/util    http://www.springframework.org/schema/util/spring-util.xsd">

    <context:component-scan base-package="com.cdi.rng"/>
    <mvc:annotation-driven/>

    <util:constant id="mediaTypeJson" static-field="org.springframework.http.MediaType.APPLICATION_JSON"/>

    <bean id="contentNegotiatingViewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="contentNegotiationManager" ref="contentNegotiationManager"/>
    </bean>
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <property name="defaultContentType" ref="mediaTypeJson"/>
    </bean>

</beans>

Here is what it looks like once the P-notation is used.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc.xsd
                           http://www.springframework.org/schema/util    http://www.springframework.org/schema/util/spring-util.xsd">

    <context:component-scan base-package="com.cdi.rng"/>
    <mvc:annotation-driven/>
    <util:constant id="mediaTypeJson" static-field="org.springframework.http.MediaType.APPLICATION_JSON"/>

    <bean id="contentNegotiatingViewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"
          p:contentNegotiationManager-ref="contentNegotiationManager"/>
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"
          p:defaultContentType-ref="mediaTypeJson"/>

</beans>
Posted in Spring | Tagged , , , , , , | 1 Comment