我正在尝试将一些字符串发送到某个php文件并获取JSON变量。 现在我坚持把我的字符串发送到我的php文件,我尝试了许多教程中的很多组合,所有这些都在粉碎:
httpclient.execute(httppost);
我真的不知道为什么。 P.S我在manifest.xml文件中给出了INTERNET权限。 这是我的代码看起来除了我以外的任何其他人。
public void send()
{
String msg = "Some message text";
if(msg.length()>0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8888/file.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);// THE APP CRASH HERE!!!
Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getBaseContext(),"All fields are required", Toast.LENGTH_SHORT).show();
}
}
目前我只想传递发送过程(接下来要处理的JSON问题)。
谢谢大家。
这是LogCat:
288-299/system_process W/ActivityManager﹕ Force finishing activity com.example.testphppost/.MainActivity
11-05 17:37:56.011 288-299/system_process W/WindowManager﹕ Failure taking screenshot for (328x546) to layer 21010
11-05 17:37:56.294 37-89/? E/SurfaceFlinger﹕ ro.sf.lcd_density must be defined as a build property
11-05 17:37:56.542 288-302/system_process W/ActivityManager﹕ Activity pause timeout for ActivityRecord{40f0e4c8 u0 com.example.testphppost/.MainActivity}
11-05 17:37:56.762 37-184/? E/SurfaceFlinger﹕ ro.sf.lcd_density must be defined as a build property
11-05 17:37:58.141 2147-2147/? I/Process﹕ Sending signal. PID: 2147 SIG: 9
11-05 17:37:58.161 288-288/system_process I/ActivityManager﹕ Process com.example.testphppost (pid 2147) has died.
11-05 17:37:59.061 288-288/system_process W/InputMethodManagerService﹕ Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@40f27770 attribute=null, token = android.os.BinderProxy@40d32668
有什么想法吗?
答案 0 :(得分:1)
很难说是因为你没有提供任何有关异常的信息,但正如Sherif elKhatib所说,你需要异步发送请求。试着看看AsyncTask。
答案 1 :(得分:1)
看起来你正试图在主线程上执行网络操作,你不能这样做。 尝试AsyncTask或打开新主题。
答案 2 :(得分:1)
您可能正在主线程上发出请求。
答案 3 :(得分:0)
android的loopback地址是10.0.2.2,但你使用localhost(表示127.0.0.1)尝试更改它。阅读本教程http://www.androidhive.info/2012/01/android-json-parsing-tutorial/