How to get JSON object using HttpURLConnection instead of Volley?

64,046

Solution 1

The url in JsonObjectRequest() is not optional, and the JSONObject parameter is used to post parameters with the request to the url.

From the documentation: http://afzaln.com/volley/com/android/volley/toolbox/JsonObjectRequest.html

http://developer.android.com/training/volley/index.html

JsonObjectRequest

public JsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener listener, Response.ErrorListener errorListener) Creates a new request.

Parameters:

method - the HTTP method to use

url - URL to fetch the JSON from

jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request.

listener - Listener to receive the JSON response

errorListener - Error listener, or null to ignore errors.

Using HttpURLConnection:

http://developer.android.com/reference/java/net/HttpURLConnection.html

The code would be something like this:

 public class getData extends AsyncTask<String, String, String> {

        HttpURLConnection urlConnection;

        @Override
        protected String doInBackground(String... args) {

            StringBuilder result = new StringBuilder();

            try {
                URL url = new URL("https://api.github.com/users/dmnugent80/repos");
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

            }catch( Exception e) {
                e.printStackTrace();
            }
            finally {
                urlConnection.disconnect();
            }


            return result.toString();
        }

        @Override
        protected void onPostExecute(String result) {

            //Do something with the JSON string

        }

    }

Solution 2

use this function

private String getJSON(String url) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-Type", "application/json; utf-8");
        c.setRequestProperty("Accept", "application/json");
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), "utf-8"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return null;
}

Solution 3

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;

    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class MyAsyncTask extends AsyncTask<URL, Void, String> {

        private HttpURLConnection urlConnection;
        private Context mContext;
        private ProgressDialog mDialog;
        private TaskListener mListener;

        public MyAsyncTask(Context context, TaskListener listener) {
            this.mContext = context;
            mDialog = new ProgressDialog(mContext);
            this.mListener = listener;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mDialog.setTitle(R.string.app_name);
            mDialog.setMessage("Retrieving data...");
            mDialog.show();
        }

        @Override
        protected String doInBackground(URL... params) {
            StringBuilder result = new StringBuilder();

            try {
                URL url = params[0];
//            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
            urlConnection = (HttpURLConnection) url.openConnection(/*proxy*/);
                urlConnection.setDoInput(true);
                urlConnection.setConnectTimeout(20 * 1000);
                urlConnection.setReadTimeout(20 * 1000);

                if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }


            return result.toString();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            mDialog.dismiss();
            mListener.onTaskComplete(s);
        }
    }
Share:
64,046
Assassin Shadow
Author by

Assassin Shadow

Rogue Programer

Updated on August 30, 2020

Comments

  • Assassin Shadow
    Assassin Shadow over 3 years

    What I'm trying to do is get some data from a HttpURLConnection instead of using JsonObjectRequest() from the Volley library.

    Below is the code that I use to grab a JSON object from my server.

    JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,"myURL", null, new Response.Listener<JSONObject>();
    

    I tried changing the null to a JSONObject after myURL was changed to null. But that did not work out.

  • Assassin Shadow
    Assassin Shadow about 9 years
    so is there a way I could fetch the JSON from a http url connection instead of a URL ? thank you
  • Daniel Nugent
    Daniel Nugent about 9 years
    @AssassinShadow Just updated the answer with code I just got working and tested.
  • Tarun Deep Attri
    Tarun Deep Attri over 8 years
    There are no parameters to your URL. Can you post some example with posting Parameters.
  • Daniel Nugent
    Daniel Nugent over 8 years
    @Terri For posting parameters take a look at this answer: stackoverflow.com/a/33031158/4409409
  • oᴉɹǝɥɔ
    oᴉɹǝɥɔ over 6 years
    The answer completely ignores response headers. "Content-Type" may contain "charset" which must be taken into account when interpreting response body.
  • Daniel Nugent
    Daniel Nugent over 6 years
    @oᴉɹǝɥɔ That is true, but headers in the response is really out of scope for this simple example.
  • Eloff
    Eloff about 6 years
    A StringBuilder (buffer), BufferedInputStream, and a BufferedReader, plus OS level socket buffering means this is quadruple buffered. No wonder some people think Java is slow - if you write code like this it could be!