74930

HTTP POST request with android crashes [duplicate]

Question:

This question already has an answer here:

<ul><li> <a href="/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception" dir="ltr" rel="nofollow">How do I fix android.os.NetworkOnMainThreadException?</a> <span class="question-originals-answer-count"> 50 answers </span> </li> </ul>

I've the following <strong>java</strong> code:

try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.1.105/test.php"); List<NameValuePair> teste = new ArrayList<NameValuePair>(1); teste.add(new BasicNameValuePair("test", "test")); httppost.setEntity(new UrlEncodedFormEntity(test)); HttpResponse response = (HttpResponse) httpclient.execute(httppost); } catch (IOException e) { e.printStackTrace(); }

Whenever I uncomment/comment the line HttpResponse response = (HttpResponse) httpclient.execute(httppost); the app crashes / doesn't crash, respectively. <strong>I have the internet permission on the manifest</strong> and I would like to obtain a json_encoded message from the server. I tried "everything" but still couldn't manage to put it to work.

Logs:

<blockquote>

07-10 15:04:30.197: E/AndroidRuntime(19382): FATAL EXCEPTION: main 07-10 15:04:30.197: E/AndroidRuntime(19382): java.lang.IllegalStateException: Could not execute method of the activity 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.view.View$1.onClick(View.java:3591) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.view.View.performClick(View.java:4084) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.view.View$PerformClick.run(View.java:16966) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.os.Handler.handleCallback(Handler.java:615) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.os.Handler.dispatchMessage(Handler.java:92) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.os.Looper.loop(Looper.java:137) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.app.ActivityThread.main(ActivityThread.java:4745) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.lang.reflect.Method.invokeNative(Native Method) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.lang.reflect.Method.invoke(Method.java:511) 07-10 15:04:30.197: E/AndroidRuntime(19382): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 07-10 15:04:30.197: E/AndroidRuntime(19382): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 07-10 15:04:30.197: E/AndroidRuntime(19382): at dalvik.system.NativeStart.main(Native Method) 07-10 15:04:30.197: E/AndroidRuntime(19382): Caused by: java.lang.reflect.InvocationTargetException 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.lang.reflect.Method.invokeNative(Native Method) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.lang.reflect.Method.invoke(Method.java:511) 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.view.View$1.onClick(View.java:3586) 07-10 15:04:30.197: E/AndroidRuntime(19382): ... 11 more 07-10 15:04:30.197: E/AndroidRuntime(19382): Caused by: android.os.NetworkOnMainThreadException 07-10 15:04:30.197: E/AndroidRuntime(19382): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 07-10 15:04:30.197: E/AndroidRuntime(19382): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 07-10 15:04:30.197: E/AndroidRuntime(19382): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 07-10 15:04:30.197: E/AndroidRuntime(19382): at libcore.io.IoBridge.connect(IoBridge.java:112) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 07-10 15:04:30.197: E/AndroidRuntime(19382): at java.net.Socket.connect(Socket.java:842) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 07-10 15:04:30.197: E/AndroidRuntime(19382): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 07-10 15:04:30.197: E/AndroidRuntime(19382): at com.diverse.just.LoginActivity.newAccount(LoginActivity.java:92) 07-10 15:04:30.197: E/AndroidRuntime(19382): ... 14 more

</blockquote>

Answer1:

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:

<a href="http://loopj.com/android-async-http/" rel="nofollow">AsyncHttpClient</a>

Answer2:

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:

class db_conn extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { GetDataFromDB db = new GetDataFromDB(); String url = params[0]; System.out.println(url); jObject = db.makeHttpRequest(url, "GET", null); return null; } .... ..... }

Answer3:

Caused by: android.os.NetworkOnMainThreadException, you can't perform network request on main thread. Move it to background.

Recommend

  • Failed to create SQLite DB in my Samsung y duos device in Android?
  • ElementListUnion - Simple xml giving duplicate annotation for generic list objects
  • VerifyError in web-service operation using SOAP only in Android 4.2?
  • SDK 25.1.0 crash on CommitNow when call within onBackStackChanged(). Google Bug?
  • java.lang.StackOverflowError error shows on making json array object?
  • Testing Private Methods Not Working
  • firebase unauth with google doesn't allow change of user
  • Bundle install fails - Gem using github url - What is wrong?
  • Doctrine: UniqueEntity with Many-to-Many field
  • What components I need to create VS 2017 offline layout for UWP development?
  • System call time out?
  • How do I recognize a line break with a switch case that evaluates a char in Java?
  • Exception in the iconization of JInternalFrame with DefaultDesktopManager
  • Android - VerifyError
  • jhipster run embedded jar with prod profile - issue with liquibase
  • Cassandra NoClassDefFoundError: com/google/common/util/concurrent/AsyncFunction
  • Invert string in Rust
  • What does certain JVM do after loading ByteCode into memory?
  • Glassfish - java.lang.NoClassDefFoundError
  • Embedded Glassfish JPA Datasource connection fail
  • Most efficient way to move table rows from one table to another
  • Error processing multiple files
  • Servlet stops working on Tomcat server after some hits or time
  • URLConnection doesn't work since API 10 and higher?
  • Access variable of ScriptContext using Nashorn JavaScript Engine (Java 8)
  • What does 'Language neutral' mean with regard to MAKELANGID?
  • Eloquent paginate function in Slim 3 project using twig
  • Problem deserializing objects from cache on MyBatis 3/Java
  • Display issues when we change from one jquery mobile page to another in firefox
  • Trying to switch camera back to front but getting exception
  • Python - Map / Reduce - How do I read JSON specific field in using DISCO count words example
  • R: gsub and capture
  • Hibernate gives error error as “Access to DialectResolutionInfo cannot be null when 'hibernate.
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • Comma separated Values
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • coudnt use logback because of log4j
  • Programmatically clearing map cache
  • How to load view controller without button in storyboard?