-1

I have been trying to get a successful JSON call from a web API with no success the past few days. I have tried multiple APIs with no success, so I don't think it is the API itself but how I am calling it with HttpURLConnection.

Here is a pruned version of my code:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView = (TextView) findViewById(R.id.textView);
    String urlString = "http://ip.jsontest.com/";
    String jsonString = null;

    HttpURLConnection connection = null;
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        InputStream stream = connection.getInputStream();

        Scanner scan = new Scanner(stream).useDelimiter("\\A");

        jsonString = scan.next();
        scan.close();

        connection.disconnect();



    } catch (Exception e) { 
        e.printStackTrace();
    } 
    textView.setText(jsonString);

}}

I have followed and used multiple tutorials and guides trying to get this to work with no avail. I have also tried using a BufferedReader and a StringBuilder to pull the data to no avail.

EDIT:

I have had made it into a separate class as well in the past to no success:

public class NetworkConnect   {

/**
 * Execute the given URI, and return the data from that URI.
 *
 * @param uri the universal resource indicator for a set of data.
 * @return the set of data provided by the uri
 */

    private Exception exception;

    HttpURLConnection connection = null;
    BufferedReader reader = null;
    protected String doInBackground(String urlString) {
        try {

            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

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

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)

            }

            return buffer.toString();


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137

1 Answers1

0

Just use an AsyncTask subclass in order to do the network operation inside thedoInBackground() method override, which is run on a background thread. Then pass the result to the onPostExecute() method override, which is run on the UI thread.

Here is a simple Activity with an AsyncTask that does what you need:

public class TestActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        textView = (TextView) findViewById(R.id.textView);

        new NetworkConnect().execute();
    }

    class NetworkConnect extends AsyncTask<Void, Void, JSONObject> {

        private static final String JSON_URL = "http://ip.jsontest.com/";
        String charset = "UTF-8";
        HttpURLConnection conn;
        StringBuilder result;
        URL urlObj;

        @Override
        protected JSONObject doInBackground(Void... args) {

            JSONObject retObj = null;

            try {
                urlObj = new URL(JSON_URL);

                conn = (HttpURLConnection) urlObj.openConnection();
                conn.setDoOutput(false);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept-Charset", charset);
                conn.setConnectTimeout(15000);
                conn.connect();

                //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("NetworkConnect", "result: " + result.toString());

                retObj = new JSONObject(result.toString());

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

            return retObj;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            //Use JSON result to display in TextView
            if (json != null) {
                textView.setText(json.toString());
            }
        }
    }
}

Note: ensure that you have the INTERNET permission in the AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137