1

i am trying to download JSON file from url using this follwing code,

 try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

However, android studio showing that HttpClient, DefaultHttpClient, HttpPost is depricated. I've tried googling for all the above deprecated options 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 way to download json file from url

neeta
  • 43
  • 12
  • Yes HttpClient is deprecated. You can use HttpUrlConnection or any good third party library like volley or retrofit etc. – Pratik Popat Feb 15 '17 at 07:12
  • use Volley Library http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ – Camahalan Royette Feb 15 '17 at 07:12
  • You could use any restAPI library like volley, okHttp or asynchttpclient. And if you really want to use your own way for fetching json then you could use OpenUrlConnection class for same. Hope it will helps you. – divyansh ingle Feb 15 '17 at 07:13
  • use volley library – Dhruv Tyagi Feb 15 '17 at 07:13
  • check this example of HttpUrlConnection https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/ – Pratik Popat Feb 15 '17 at 07:14
  • 1
    Possible duplicate of [Android deprecated apache module (HttpClient, HttpResponse, etc.)](http://stackoverflow.com/questions/29294479/android-deprecated-apache-module-httpclient-httpresponse-etc) – g00glen00b Feb 15 '17 at 07:16

3 Answers3

1
use this HttpClient httpClient = HttpClientBuilder.create().build();

or you can use

import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        conn.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jObj;
    }
}
Vinay
  • 732
  • 5
  • 8
0

If you do not mind using gson

String someUrl = "http://freegeoip.net/json/";

URL url = new URL(someUrl);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();

JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
someProperty= rootobj.get("some_property").getAsString();
mirzak
  • 1,043
  • 4
  • 15
  • 30
0
    These are few workarounds;

    1) Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead. This API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption. 
    To continue using the Apache HTTP APIs, you must first declare the following compile-time dependency in your build.gradle file:

    android 
    {
        useLibrary 'org.apache.http.legacy'
    }

    Following is the link for your reference:
    https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#boringSSL
    2) If you have considerable amount of time to make changes, there are few third party open source libraries available out there such as retrofit (written by Square: https:/square.github.io/retrofit/) , volley( written by Google) which are much compact, efficient and easy to use.
Hope this helps. Happy Coding.