尝试使用HttpURLConnection添加令牌并建立连接时获取NetworkOnMainThreadException

时间:2015-09-26 18:19:29

标签: android httpclient

下面是我的代码,当我尝试从我的应用程序进行httpconnect并进行API调用时。我收到android.os.NetworkOnMainThreadException。我该怎么做才能修复我的代码。

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();

0 个答案:

没有答案