问题
I am using android 2.3.3, i had made an rss reader which was working great, then i integrated the code of that simple rss reader into another activity, just copy pasted it carefully, no errors there.
The problem is when i run the app on my emulator it gives me error connecting exception. Then i figured out by putting toasts after everyline in try block that the problem is at httpconnection.connect();
line.
I have added the permission in the android manifest while my logcat gives a warning of javaio exception:error connecting
.
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 the code which creates the object:
URL url = new URL(UrlString);
URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection))
throw new IOException("Not a HTTP connection");
回答1:
It gives networkonmainthread exception
This means that you are doing network operations on the main thread, and that's not allowed in the Strict Mode.
"In the main thread" usually means that you are doing it in the event handlers, like onResume
, onPause
, or in the onClick
method of your OnClickListener. You may look at this post (Painless threading) to understand what's the problem and why this is not allowed. Generally, if you perform network operations in the main thread, it would block the processing of GUI events, and if the network operation was slow, your application would be not responsive.
Strict Mode appeared in API level 9, so this explains that why you have problem if min SDK version is 10, and why it works with min SDK version 8.
You should use AsyncTask or other methods to do it in the background. You may refer to 1 for this.
来源:https://stackoverflow.com/questions/11282610/cannot-connect-using-httpconnection-in-android