Java – cannot connect using HTTPCONNECTION in Android

I'm using Android 2.3 3. I have made an RSS reader that works well, and then I integrate the code of the simple RSS reader into another activity. Just copy and paste it without error

The problem is that when I run the application on my simulator, it gives an error of connection exception Then I solve the problem by placing toast after each line in the try block, which is in HTTPCONNECTION connect(); Line.

I added permissions to the Android list, and my logcat issued a Java IO exception warning: connection error

try {
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        //Toast.makeText(this,"urlconnection passed",Toast.LENGTH_SHORT).show();
        httpURLConnection.setAllowUserInteraction(false);
        httpURLConnection.setInstanceFollowRedirects(true);
        //Toast.makeText(this,"setting response method",Toast.LENGTH_SHORT).show();
        httpURLConnection.setRequestMethod("GET");
        //Toast.makeText(this,"connecting",Toast.LENGTH_SHORT).show();
        httpURLConnection.connect();
        Toast.makeText(this,"on response code",Toast.LENGTH_SHORT).show();
        response = httpURLConnection.getResponseCode();
        //Toast.makeText(this,"response code passed",Toast.LENGTH_SHORT).show();
        if (response == HttpURLConnection.HTTP_OK) {
            //Toast.makeText(this,"OK",Toast.LENGTH_SHORT).show();
            inputStream = httpURLConnection.getInputStream();
        }

    } catch (Exception e) {
        // TODO: handle exception
        throw new IOException("Error connecting");
    }

Here is the code to create the object:

URL url = new URL(UrlString);
URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) 
  throw new IOException("Not a HTTP connection");

Solution

This means that you are performing network operations on the main thread and are not allowed to do so in strict mode

"In main thread" usually means that you perform this operation in an event handler, such as onresume, onpause, or onclicklistener's onclick method You can check out this article (painless threading) to see what the problem is and why this is not allowed Usually, if you perform network operation in the main thread, it will prevent the processing of GUI events. If the network operation is very slow, your application will not respond

Strict mode appears at API level 9, so this explains why if the Min SDK version is 10 and why it has problems when used with min SDK version 8

You should use asynctask or other methods to perform this operation in the background You can refer to 1

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>