[Java] Create a Simple Http Get Request with GZip Compression Handling using Apache Httpclient

Previous Apache HttpClient use various class to handling compressed http response, such as DecompressingHttpClient and ContentEncodingHttpClient. But on the latest version, compression is handled automatically by using HttpClientBuilder class.

Here is my pom file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.edw</groupId>
    <artifactId>Edw</artifactId>
    <version>1</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    
    <dependencies>                
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>        
    </dependencies>
    
</project>

And this is my java class,

package com.edw.main;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Main {

    public static void main(String[] args) throws Exception {
        Main main = new Main();
        System.out.println(main.getContent("http://localhost:8085/"));
    }

    private String getContent(String urlToRead) throws Exception {
        HttpEntity resEntity = null;
        try {
            HttpClient httpclient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(urlToRead);

            HttpResponse response = httpclient.execute(httpGet);
            resEntity = response.getEntity();

            return EntityUtils.toString(resEntity);
        } finally {
            if (resEntity != null) {
                EntityUtils.consume(resEntity);
            }
        }
    }
}
Google+

No Comments

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)