2012-12-17 145 views
0

我想使用http post請求將一些數據插入到數據庫中。 我post.php中頁是:Android:通過url傳遞參數

 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'].")"; 
      [...] 

,並以發送數據,我附上所有的URL參數,如:​​

,一切工作正常,但是當我試圖把我的來自我的Android應用程序的數據無法達到我的目標。 如何通過網址傳遞數據? 在Android中我已經試過:

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) 

,並用:

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(); 

,但我總是錯誤。 使用第二種方法的例外是:

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) 

我該怎麼辦?

+1

不要運行您的網絡操作在UI線程上。看看這裏:http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Eric

+0

我在一個處理程序中運行我的網絡操作,它不在主線程內。 – Ant4res

+1

除非你已經在另一個線程中啓動處理程序,它仍然會在主線程上運行 – nandeesh

回答

1

NetworkOnMainThreadException網絡請求:

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

意味着你正在嘗試運行從UI線程網絡操作,以便把所有與網絡相關的代碼中AsyncTaskdoInBackground方法當doInBackground方法執行完成時使用onPostExecute更新UI

如果您正在使用API LEVEL 9或更高FROM 9那麼的onCreate添加StrictMode活動,以避免這個錯誤

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 
       .detectDiskReads() 
       .detectDiskWrites() 
       .detectNetwork() 
       .penaltyLog() 
       .build()); 
0

您收到NetworkOnMainThreadException例外。您需要將網絡請求代碼移到另一個線程或使用Asynctask。

你不能對主線程

+0

好的,但我在處理程序中運行我的postData()方法。 – Ant4res

+0

Handler只是一個幫助程序異步運行代碼,它仍然會在主線程上運行代碼。你將不得不在不同線程中創建處理器,這個線程已經準備好了,只有當它使用'API LEVEL 9或者GREATER FROM 9'時,它才能工作 – nandeesh

+1

,然後我們將使用'StrictMode'從Ui線程創建網絡,並且不需要使用'Asynctask',但最好使用'Asynctask'來讓你的代碼更加可重用 –

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.

要想從這個異常無更好的方式來在的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(); 

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy);