-1

I have been using this code to get JSON from a specified URL, but today I checked it, and everything in it is deprecated. It still works fine, but I want to know what is the new method of doing it?

Here's what I have:

    @Override
    protected String doInBackground(String... params) {
        try {
            HttpClient client = new DefaultHttpClient();
            StringBuilder url = new StringBuilder("some url");
            HttpGet hg = new HttpGet(url.toString());
            HttpResponse hr = client.execute(hg);
            int status = hr.getStatusLine().getStatusCode();
            if (status == 200) {
                HttpEntity he = hr.getEntity();
                String data = EntityUtils.toString(he);
                jsonGet = new JSONObject(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

The deprecated objects are HttpClient, HttpGet, HttpResponse, HttpEntity and EntityUtils.

EDIT: As suggested in some questions, this way

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

does not work for me, as I am getting HttpClientBuilder cannot be resolved

Gopal Singh Sirvi
  • 4,539
  • 5
  • 33
  • 55
Borislav
  • 909
  • 3
  • 10
  • 25

2 Answers2

1

Apache httpClient is deprecated with api level 22 you can read it about this blog.

there is a new client for android now and it is very good.

but you can use okhttp instead (also back compat is possible).

EDIT check this link(URL.openConnection()). this blog was posted in 2011 but they mentioned the deprecation there first as far as i know.

Ercan
  • 3,705
  • 1
  • 22
  • 37
0

First of all you have to search well on Google.

Here is your answer may it will helps you.

The HttpClient documentation points you in the right direction:

org.apache.http.client.HttpClient:

This interface was deprecated in API level 22. Please use openConnection() instead. Please visit this webpage for further details.

means that you should switch to java.net.URL.openConnection().

Here's how you could do it:

URL url = new URL("http://some-server");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");

// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);

IOUtils documentation: Apache Commons IO
IOUtils Maven dependency: http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar

Special Thanks to fateddy for this answer

Community
  • 1
  • 1
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437