dpir3950
dpir3950
2012-12-17 17:11

Android:通过url传递参数

已采纳

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongzhang1875 dongzhang1875 9年前

    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());
    
    点赞 评论 复制链接分享
  • dsgm5631 dsgm5631 9年前

    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); 
    
    点赞 评论 复制链接分享
  • drvkf88226 drvkf88226 9年前

    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

    点赞 评论 复制链接分享