Java Apache DefaultHttpClient deprecated

 Posted On  | Yashwant Chavan 

Recently I have migrated my old http client request/response utility methods to latest Apache HttpClient version (4.5.2). Because in most of the request methods Eclipse shows warning message as The type DefaultHttpClient is deprecated. So I have modified my code base with new way to get the HttpClient instance.

Refer below steps.

  • Old way - Create HttpClient instance using new DefaultHttpClient(), Which is marked as deprecated in latest version.
  • New way - Create HttpClient instance using new HttpClientBuilder.create().build() instead of DefaultHttpClient

Using DefaultHttpClient

public void get() {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://www.technicalkeeda.com");
        HttpResponse response = client.execute(request);
        ...
        ...
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (UnsupportedOperationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Using HttpClientBuilder.create().build()

package com.technicalkeeda.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpClientExample {
    public static void main(String[] args) {
        HttpClientExample client = new HttpClientExample();
        System.out.println("Http Get Request");
        client.get();
    }

    public void get() {
        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet("http://www.technicalkeeda.com");
            HttpResponse response = client.execute(request);
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line = "";
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0226 seconds.