0

Below is my code,While I am trying to do httpconnect from my app and make an API call.I am getting android.os.NetworkOnMainThreadException.What Can I do to fix my code.

URL url = new URL("http://sampleurl.com");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        conn.addRequestProperty("X-APP-Token", "value");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        System.out.println("wILL ESTABLISH CON");
        Log.i("Net", "length=" + conn.getContentLength());
        Log.i("Net", "contentType=" + conn.getContentType());
        Log.i("Net", "content=" + conn.getContent());
        conn.connect();
        int response = conn.getResponseCode();
        Toast.makeText(getApplicationContext(),"CODE" + conn.getResponseCode(),Toast.LENGTH_LONG).show();
        System.out.println("RESPONSE " + response);
        InputStream in = conn.getInputStream();
  • @CommonsWare I am not Using SAXParseFactory, I am using HttpURLConnection .Can you please check whats the issue? – Lucky Ragava Sep 26 '15 at 18:24
  • "I am not Using SAXParseFactory, I am using HttpURLConnection" -- that does not matter. There are many, many answers on that question that cover how to address a `NetworkOnMainThreadException`. – CommonsWare Sep 26 '15 at 18:26
  • @CommonsWare none of them fits under my use case – Lucky Ragava Sep 26 '15 at 18:31
  • The solutions outlined in those answers (`AsyncTask`, `IntentService`, ordinary background thread, etc.) cover pretty much every use case. Feel free to explain, **in detail**, what your use case is that these techniques do not address. – CommonsWare Sep 26 '15 at 18:36

0 Answers0