0

I am trying to call a url which has json data.

String response = null;
    try {
        URL url = new URL("https://demorul.com");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json;odata=verbose");
        conn.setRequestProperty("Accept", "application/json;odata=verbose");

        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;

The url will return json data. But i am getting android.os.NetworkOnMainThreadException error mean its goes to last catch statement.

In AndroidManifest.xml file i have set

<uses-permission android:name="android.permission.INTERNET"/>

Thanks

1 Answers1

1

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask

Tung Tran
  • 2,885
  • 2
  • 17
  • 24