Http Post Request With Android Crashes
I've the following java code: try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost('http://192.168.1.105/test.php'); List
Solution 1:
You must execute the HTTP request part on another Thread.
For example:
AsyncTask<String, Void, Void> db = null;
try {
db = new db_conn(this);
db.execute("http://192.168.1.5/request.php").get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
the .get() method waits for the AsyncTask to finish before the main thread continue its execution.
And the db class:
classdb_connextendsAsyncTask<String, Void, Void> {
@OverrideprotectedVoiddoInBackground(String... params) {
GetDataFromDB db = newGetDataFromDB();
String url = params[0];
System.out.println(url);
jObject = db.makeHttpRequest(url, "GET", null);
returnnull;
}
....
.....
}
Solution 2:
You should put your code in the AsyncTask
for background performance.
But for a better way of downloading Server data use a framework called AsyncHttpClient, you can find it here:
Solution 3:
Caused by: android.os.NetworkOnMainThreadException
, you can't perform network request on main thread. Move it to background.
Post a Comment for "Http Post Request With Android Crashes"