Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I am getting DefaultHttpClient is deprecated?

I am working on a project in which I need to make a call to my service and my service will return the data back in JSON format. And I don't need to serialize this JSON response to any POJO, I just need to get the data back as String. And this application is very performance critical so HttpClient has to be pretty fast

So I decided to use Apache HttpClient or is there any better alternative which I can use?

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("some-url");
request.addHeader("Context", "some-value");
HttpResponse response = httpClient.execute(request);
String response =  IOUtils.toString(response.getEntity().getContent(), "UTF-8");

But it complains that The type DefaultHttpClient is deprecated so maybe they have new version of HttpClient or some other way of making a HttpClient call to an URL?

Is there anything I am missing?

like image 672
john Avatar asked Jul 16 '14 18:07

john


2 Answers

Use this:

HttpClient httpclient = HttpClientBuilder.create().build();

Refer to this stackoverflow post

like image 107
arsenal Avatar answered Oct 16 '22 02:10

arsenal


From Apache HTTP Client API version 4.3 on wards, DefaultHttpClient is deprecated.

Use following maven dependency as an example.

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

Following import.

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGett;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.methods.HttpUriRequest;

Following code block.

HttpClient client = HttpClientBuilder.create().build();
HttpUriRequest httpUriRequest = new 
HttpGet("http://example.domain/someuri");

HttpResponse response = client.execute(httpUriRequest);
System.out.println("Response:"+response);
like image 5
Red Boy Avatar answered Oct 16 '22 03:10

Red Boy