我想通过POST方法发送字符串,但是出现此错误而我找不到,你能帮助我吗?
这给出了一个非常奇怪的异常,APA没有打开,现在出现错误,MainActivity屏幕不会出现。
我的代码:
MainActivity.java
package com.app.androidpost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.meusite.com/ws/default.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "Sucesso"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseText = EntityUtils.toString(response.getEntity());
Toast.makeText(this, responseText , 5000).show();
}
catch (ClientProtocolException e) {
Toast.makeText(this, "Erro Conversão" , 5000).show();
}
catch (IOException e) {
Toast.makeText(this, "Erro conexão" , 5000).show();
}
}
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.androidpost"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.app.androidpost.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
PHP代码
<?php
$reversed = $_POST["action"];
echo $reversed;
?>
logcat的
01-20 18:42:03.909: W/dalvikvm(25243): threadid=1: thread exiting with uncaught exception (group=0x40dab1f8)
01-20 18:42:03.949: E/AndroidRuntime(25243): FATAL EXCEPTION: main
01-20 18:42:03.949: E/AndroidRuntime(25243): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.androidpost/com.app.androidpost.MainActivity}: android.os.NetworkOnMainThreadException
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1960)
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1985)
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.app.ActivityThread.access$600(ActivityThread.java:127)
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1151)
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.os.Looper.loop(Looper.java:137)
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.app.ActivityThread.main(ActivityThread.java:4476)
01-20 18:42:03.949: E/AndroidRuntime(25243): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 18:42:03.949: E/AndroidRuntime(25243): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 18:42:03.949: E/AndroidRuntime(25243): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:816)
01-20 18:42:03.949: E/AndroidRuntime(25243): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:583)
01-20 18:42:03.949: E/AndroidRuntime(25243): at dalvik.system.NativeStart.main(Native Method)
01-20 18:42:03.949: E/AndroidRuntime(25243): Caused by: android.os.NetworkOnMainThreadException
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
01-20 18:42:03.949: E/AndroidRuntime(25243): at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
01-20 18:42:03.949: E/AndroidRuntime(25243): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
01-20 18:42:03.949: E/AndroidRuntime(25243): at java.net.InetAddress.getAllByName(InetAddress.java:251)
01-20 18:42:03.949: E/AndroidRuntime(25243): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-20 18:42:03.949: E/AndroidRuntime(25243): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-20 18:42:03.949: E/AndroidRuntime(25243): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-20 18:42:03.949: E/AndroidRuntime(25243): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-20 18:42:03.949: E/AndroidRuntime(25243): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-20 18:42:03.949: E/AndroidRuntime(25243): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-20 18:42:03.949: E/AndroidRuntime(25243): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-20 18:42:03.949: E/AndroidRuntime(25243): at com.app.androidpost.MainActivity.onCreate(MainActivity.java:38)
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.app.Activity.performCreate(Activity.java:4636)
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1051)
01-20 18:42:03.949: E/AndroidRuntime(25243): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1924)
01-20 18:42:03.949: E/AndroidRuntime(25243): ... 11 more
非常感谢
答案 0 :(得分:0)
您遇到错误,因为您尝试在主线程中连接到网络,这是不允许的 正如您可以阅读here:
应用程序尝试执行时抛出的异常 主线程上的网络操作。 这仅适用于针对Honeycomb SDK或。的应用程序 更高。允许使用早期SDK版本的应用程序 他们的主要事件循环线程上的网络,但它是很重要的 泄气。请参阅文档设计响应性。
你必须使用后台线程,例如AsyncTask。你有一个简单的guide here
您的代码将是这样的:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new HttpTask().execute("http://www.meusite.com/ws/default.php");
}
private class HttpTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[i]);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "Sucesso"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseText = EntityUtils.toString(response.getEntity());
Toast.makeText(this, responseText , 5000).show();
}
catch (ClientProtocolException e) {
Toast.makeText(this, "Erro Conversão" , 5000).show();
}
catch (IOException e) {
Toast.makeText(this, "Erro conexão" , 5000).show();
}
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) { }
protected void onPostExecute(Long result) { }
}
}