0

I want to insert some data into a database using a http post request. My post.php page is:

      if(trim($_GET['param1'])!="" && trim($_GET['param2'])!="" && trim($_GET['param3'])!="" && trim($_GET['param4'])!="" && trim($_GET['param5'])!="")
{
    $connectionInfo = array(  "UID" => $DB_USER,  "PWD" => $DB_PASS, "Database"=>$DB_DATABASE );
    $con = sqlsrv_connect($DB_SERVER,$connectionInfo);
    if(!$con)
    {
      die('Could not connect: ' . sqlsrv_errors());
    }
    $query="INSERT INTO Table (param1,param2,param3,param4,param5) VALUES (
            '".$_GET['param1']."',
            ".$_GET['param2'].",
            ".$_GET['param3'].",
            '".$_GET['param4']."',
            ".$_GET['param5'].")";
            [...]

and in order to send data, I append all the parameters to the url, like: http://<myip>/MySite/post.php?param2=10&param3=8&param1=2012-12-01 13:00:00&param4=Name&param5=80

and everything works fine, but when I try to send my data from my Android application I could not achive my target. How can I pass data via url? In Android I've tried:

    HttpPost httppost = new HttpPost("http://<Myip>/MySite/post.php");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
    nameValuePairs.add(new BasicNameValuePair("param2", "10"));
    nameValuePairs.add(new BasicNameValuePair("param3", "98"));
    nameValuePairs.add(new BasicNameValuePair("param1", "2012-12-01 13:00:00"));
    nameValuePairs.add(new BasicNameValuePair("param4", "Name"));
    nameValuePairs.add(new BasicNameValuePair("param5", "50"));
    //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost)

and with:

String urlParameters = "param1=2012-12-01 13:00:00&param2=b&param3=c...";
String request = "http://<Myip>/MySite/post.php";
URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", ""  Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();

but I always get errors. Using second method the exception is:

12-17 18:08:26.617: E/AndroidRuntime(4837): FATAL EXCEPTION: main
12-17 18:08:26.617: E/AndroidRuntime(4837): android.os.NetworkOnMainThreadException
12-17 18:08:26.617: E/AndroidRuntime(4837):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.io.IoBridge.connect(IoBridge.java:112)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at java.net.Socket.connect(Socket.java:842)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:77)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at  com.example.applic.applic.postData(MyApp.java:197)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at com.example.applic.applic$1.run(MyApp.java:127)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at android.os.Handler.handleCallback(Handler.java:605)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at android.os.Looper.loop(Looper.java:137)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at android.app.ActivityThread.main(ActivityThread.java:4514)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at java.lang.reflect.Method.invokeNative(Native Method)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at java.lang.reflect.Method.invoke(Method.java:511)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
12-17 18:08:26.617: E/AndroidRuntime(4837):     at dalvik.system.NativeStart.main(Native Method)

What can I do?

Ant4res
  • 1,217
  • 1
  • 18
  • 36
  • 1
    Don't run your network operations on the UI thread. Have a look here: http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Cat Dec 17 '12 at 17:12
  • I run my network operation inside an handler, it's not inside the main thread. – Ant4res Dec 17 '12 at 17:13
  • 1
    unless you have started handler in another thread, it will still run on the main thread – nandeesh Dec 17 '12 at 17:14
  • nandeesh is right. And again, notice the name of your error: `NetworkOnMainThreadException`. – Cat Dec 17 '12 at 17:15
  • 1
    search networkonmainthread, to begin with (-1 for not searching this term, there are literally thousands of article on that topic). then, you are using post for get. you use _GET in PHP, which would indicate you want to receive a GET request. but you use an HttpPost and then a Post request, which indicates otherwise. – njzk2 Dec 17 '12 at 17:44

3 Answers3

1

NetworkOnMainThreadException :

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

means you are trying to run network operation from UI Thread so put your all network related code inside AsyncTask's doInBackground method and use onPostExecute for updating UI when doInBackground method execution complete

and if your are using API LEVEL 9 or GREATER FROM 9 then add StrictMode in onCreate of Activity to avoid this error

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()  
                 .penaltyLog()
                 .build());
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

You are getting a NetworkOnMainThreadException exception. You need to move the Network request code onto another Thread or use an Asynctask.

You cannot make network requests on Main thread

nandeesh
  • 24,740
  • 6
  • 69
  • 79
  • Ok, but I run my postData() method inside an handler. – Ant4res Dec 17 '12 at 17:14
  • Handler is just a helper to run the code asynchronously, it will still run the code on main thread. You will have to create the handler in a different thread which has looper prepared, only then will it work – nandeesh Dec 17 '12 at 17:16
  • 1
    if we are using `API LEVEL 9 or GREATER FROM 9` then we will make network from Ui thread by using `StrictMode` and without using `Asynctask` but it's better to use `Asynctask` to make your code more reusable – ρяσѕρєя K Dec 17 '12 at 17:26
0

This exception is thrown when an application attempts to perform a networking operation on its main thread which is not allowed in android version >= 3.

To get free from this exception better way to run your code in AsyncTask:

class BackTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... arg) {
        //Implement Logic you want to perform in background.
    }

    protected void onPostExecute(Void feed) {
       //Implement logic whatever you want to perform after task complete.
    }
 }

new BackTask().execute();

OR

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
Ajay S
  • 48,003
  • 27
  • 91
  • 111