我想使用http post请求将一些数据插入数据库。 我的post.php页面是:
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'].")";
[...]
为了发送数据,我将所有参数附加到网址,例如:http://<myip>/MySite/post.php?param2=10¶m3=8¶m1=2012-12-01 13:00:00¶m4=Name¶m5=80
并且一切正常,但当我尝试从我的Android应用程序发送数据时,我无法实现目标。 如何通过url传递数据? 在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¶m2=b¶m3=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)
我该怎么办?
答案 0 :(得分:1)
应用程序尝试执行时抛出的异常 在其主线程上进行网络操作。
表示您尝试从UI线程运行网络操作,因此将所有与网络相关的代码放在AsyncTask的doInBackground
方法中,并在onPostExecute
时使用doInBackground
更新UI方法执行完成
如果您使用 API LEVEL 9或GREATER FROM 9 ,请在onCreate of Activity中添加StrictMode以避免此错误
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
答案 1 :(得分:0)
您收到NetworkOnMainThreadException
个例外。您需要将网络请求代码移动到另一个线程或使用Asynctask。
您无法在主线程上发出网络请求
答案 2 :(得分:0)
当应用程序尝试在其主要线程上执行网络操作时抛出此异常,这在Android版本&gt; = 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);