The type DefaultHttpClient is deprecated

Eclipse IDE prompts warning on new DefaultHttpClient, mark this class as deprecated.


package com.mkyong.web.controller;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class WebCrawler {

	public static void main(String[] args) throws Exception {

		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet("https://mkyong.com");
		HttpResponse response = client.execute(request);
		//...

	}

}

Solution

Dive into the source code, see this comments :

DefaultHttpClient.java

 * @deprecated (4.3) use {@link HttpClientBuilder}.
 */
@ThreadSafe
@Deprecated
public class DefaultHttpClient extends AbstractHttpClient {
	//...

To solve it, use HttpClientBuilder :


package com.hostingcompass.web.controller;

import org.apache.http.Header;
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;

public class WebCrawler {

	public static void main(String[] args) throws Exception {

		HttpClient client = HttpClientBuilder.create().build();
		HttpGet request = new HttpGet("https://mkyong.com");
		HttpResponse response = client.execute(request);
		//...
	
	}

}

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
sammy
12 years ago

How to use HttpClientBuilder in thread safe way

diego
2 years ago

thank you so much

pravin
7 years ago

can I use this HttpClient httpClient=new HttpClient(); then GetMethod getmethod=new GetMethod(URL); then int statusCode=httpClient.execute(getMethod);

peacefulZen
7 years ago

Just wanted to thank you for all of your great Java tutorial’s over the years! They have been a life saver more than once: )

This one is no exception!

NewBie
9 years ago

While using “import org.apache.http.client.*” can’t be resolved message is being given. Has the “http.client” been deprecated as i don’t see “http.client” in httpcore-4.1.2.jar and others. Please tell which to use as alternative for this ?

????? ???????
10 years ago

Thanks!!!

burnt_apples
11 years ago

HttpClient is still deprecated no matter how you instantiate it. The suggested alternatives are OkHttp and HttpUrlConnection, or setting HttpClient from apache as a dependency.

Personally, i recommend OkHttp. It’s very easy to put your post data into a JSON-form string, and largely improves on HttpUrlConnection.

Side tip – if you switch away from apache, you’ll need to figure out how to handle cookies. OkHttp allows you to do this very easily

Thomas Rogers
12 years ago

Note however, that DefaultHttpClient is threadsafe, but HttpClientBuilder is not.