Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

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;
    }

December 10th, 2014

Posted In: Java

Tags: , , , ,

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By : XYZScripts.com