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);
//...
}
}
How to use HttpClientBuilder in thread safe way
can I use this HttpClient httpClient=new HttpClient(); then GetMethod getmethod=new GetMethod(URL); then int statusCode=httpClient.execute(getMethod);
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!
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 ?
Thanks!!!
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
Note however, that DefaultHttpClient is threadsafe, but HttpClientBuilder is not.