Basic Basic - 2 years ago 173
Java Question

Deprecated Java HttpClient - How hard can it be?

All I'm trying to do is download some JSON and deserialize it into an object. I haven't got as far as downloading the JSON yet.

Almost every single HttpClient example I can find, including those on the apache site looks something like...

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

public void blah() {
HttpClient client = new DefaultHttpClient();

However, Netbeans tells me that
is deprecated. I've tried googling for
DefaultHttpClient deprecated
and as many other variations as I can think of and can't find any useful results, so I'm obviously missing something.

What is the correct Java7 way to download the contents of a webpage? Is there really no decent Http Client as part of the language? I find that hard to believe.

My Maven dependency for this is...


Answer Source

Relevant imports:

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;


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

EDIT (after Jules' suggestion):

As the build() method returns a CloseableHttpClient which is-a AutoClosable, you can place the declaration in a try-with-resources statement (Java 7+):

try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

    // use httpClient (no need to close it explicitly)

} catch (IOException e) {

    // handle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download