Android Http Connection Exception

Android http connection exception

Caused by: android.os.NetworkOnMainThreadException

In Honeycomb they've gone and put in a trap to catch people trying to do potentially time-consuming network operations on the main thread.

From: http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.

Also see StrictMode.

(Please note that you could have instantly found this yourself by doing a web search on the exception at the top of the error messages you posted.)

Because things like looking up a host name can take a long and somewhat indeterminate amount of time, they should not be called from the event functions on the main thread which are required to return quickly (as in within a few milliseconds). If one of these functions takes too long to return, Android loses the ability to send messages to the program, and may pop up the dreaded Application Not Responding dialog.

You should move your networking operations (at least any that require waiting for a result or for a blockage to clear so you can send more) to a thread. If the network operations are coming from an piece of API code, you probably shouldn't be calling that on the main thread.

Getting Exception at HttpConnection.connect() android

Try this..

TextView txt;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txt = (TextView) findViewById(R.id.text);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new DownloadText("http://www.edumobile.org/android/").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new DownloadText("http://www.edumobile.org/android/").execute(new String[]{null});

}

public class DownloadText extends AsyncTask<String, Void, String> {

// variables passed in:
String urls;
// constructor
public DownloadText(String urls) {
this.urls = urls;
}

@Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(httpsData.this, "Fetching Details..", "Please wait...", true);
}

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub

int BUFFER_SIZE = 2000;
InputStream in = null;
try {

InputStream in = null;
int response = -1;

URL url = new URL(urls);

URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
{
throw new IOException("Not an HTTP connection");
}

HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}

@Override
protected void onPostExecute(String result) {
// Now we have your JSONObject, play around with it.
if (pDialog.isShowing())
pDialog.dismiss();

if(!result.equals(""))
txt.setText(result);
}

}

HttpUrlConnection.connect throws an exception

Use this line of code

       Thread background = new Thread(new Runnable() {

// After call for background.start this run method call
public void run() {
try {

HashMap<String,String> hm = new HashMap<>();
hm.put("name", et2.getText().toString());
hm.put("friend_name", et.getText().toString());
URL url = new URL("http://wwtbamandroid.appspot.com/rest/friends");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.connect();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), "UTF-8"));
writer.write(getPostDataString(hm));
writer.flush();
writer.close();

} catch (Throwable t) {
// just end the background thread
Log.i("Animation", "Thread exception " + t); }
}

});
// Start Thread
background.start();

Android http connection refused

It is impossible to use long network connections in background on Xiaomi phones. It's MIUI blocks any network connections after some time. For critical network connections, you can use Firebase Cloud Messaging, which have high priority in Android system. It can initiate necesary background job.

mysterious exception when use Http URL Connection

You are doing long time operations in the main thread that throws an Exception

android.os.NetworkOnMainThreadException


Use Async Task

new AsyncTask<String,String,String>(){

@Override
protected String doInBackground(String... params) {

//Your HTTP Request goes here

return response;
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("UpdateJSON ", s);
if(!s.equalsIgnoreCase("null") || !s.equalsIgnoreCase(""))
writeManifestJSON(s);
}
}.execute();


OR

I solved this problem using a new Thread. Which will not work in the main thread.

Thread thread = new Thread(new Runnable() {

@Override
public void run() {
try {
//Your HTTP Request goes here
} catch (Exception e) {
e.printStackTrace();
}
}
});

thread.start();


Error in http connection

you need to put permission tag put of application tag...

How to treat HttpURLConnection when failed to connect to URL

Since there is no catch block in your code, you are not catching any exceptions currently.

If you would like to handle the ConnectException, then you simply have to catch it:

override fun doInBackground(vararg url: String?): String {
var text = ""
var connection: HttpURLConnection? = null

try {
connection = URL(url[0]).openConnection() as HttpURLConnection
connection.connect()
text = connection.inputStream.use {
it.reader().use { reader ->
reader.readText()
}
}
} catch (ce: ConnectException) {
// ConnectionException occurred, do whatever you'd like
ce.printStackTrace()
} catch (e: Exception) {
// some other Exception occurred
e.printStackTrace()
} finally {
connection?.disconnect()
}

return text
}

Check out the Exceptions reference.

I am trying http connection over android

rather using httpconnection i would suggest you to use httpclient
like

          try
{
HttpClient client=new DefaultHttpClient();
HttpPost request=new HttpPost("your url");

BasicNameValuePair email=new BasicNameValuePair("username", "your username");
BasicNameValuePair password=new BasicNameValuePair("password", "your password");

List<NameValuePair> list=new ArrayList<NameValuePair>();
list.add(username);
list.add(password);

UrlEncodedFormEntity urlentity=new UrlEncodedFormEntity(list);
request.setEntity(urlentity);

HttpResponse response=client.execute(request);

HttpEntity entity=response.getEntity();
String tmp=EntityUtils.toString(entity);
return tmp;
}
catch(Exception e)
{
return e.toString();
}

try yourcode with this...and tell me ...i'll surelly work...and its also quite simple...there its all meshup with stream and all.. hope this will help... ;-)

Android HTTP Connection refused

Problem solved. The issue was a corrupted manifest file. I deleted the permission lines and re-typed them in and now the problem is gone



Related Topics



Leave a reply



Submit