如何使用httpPost将数据发送到网站,应用程序崩溃
目前我正在开展一个项目。 我需要从我的Android应用程序发送一些数据到网络服务器。 但当我触摸发送按钮时,应用程序崩溃了。
这是我的.java文件
package com.androidexample.httppostexample; import java.io.IOException; import org.apache.http.client.ClientProtocolException; import java.util.ArrayList; import java.util.List; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class HttpPostExample extends Activity { Button sendButton; EditText msgTextField; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // load the layout setContentView(R.layout.activity_http_post_example); // make message text field object msgTextField = (EditText) findViewById(R.id.msgTextField); // make send button object sendButton = (Button) findViewById(R.id.sendButton); } // this is the function that gets called when you click the button public void send(View v) { // get the message from the message text box String msg = msgTextField.getText().toString(); // make sure the fields are not empty if (msg.length()>0) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.eeecoderpages.orgfree.com/post.php"); try { List nameValuePairs = new ArrayList(2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("message", msg)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpclient.execute(httppost); msgTextField.setText(""); // clear text box } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } } else { // display message if text fields are empty Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); } } }
这是我的xml gui文件:
我还为清单添加了Internet权限:
在网络服务器端,我使用了以下php脚本 :
<?php // get the "message" variable from the post request // this is the data coming from the Android app $message=$_POST["message"]; // specify the file where we will save the contents of the variable message $filename="androidmessages.html"; // write (append) the data to the file file_put_contents($filename,$message."
",FILE_APPEND); // load the contents of the file to a variable $androidmessages=file_get_contents($filename); // display the contents of the variable (which has the contents of the file) echo $androidmessages; ?>
但它不起作用。 当我触摸发送按钮时,系统关闭了我的应用程序。 我搜索了很多解决方案,但是没有解决方案适合我。 任何身体的任何帮助,我将不胜感激!
UI主线程上的网络操作是不允许的。
请尝试以下代码。
public class NetRequestAsync extends AsyncTask { String id, msg; public NetRequestAsync(String id, String message) { this.id = id; this.msg = message; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Boolean doInBackground(Void... params) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://www.eeecoderpages.orgfree.com/post.php"); try { List nameValuePairs = new ArrayList ( 2); nameValuePairs.add(new BasicNameValuePair("id", id)); nameValuePairs.add(new BasicNameValuePair("message", msg)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpclient.execute(httppost); return true; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if(result){ //successful request }else{ //error in request response } msgTextField.setText(""); // clear text box } }
要使用此代码,
NetRequestAsync request = new NetRequestAsync("12345","Hi"); request.execute();
注意
在doInBackground()
方法中不允许更新TextView,EditText或将图像设置为ImageView等UI操作。 您可以在onPostExecute()
或onPreExecute()
。
您正在主ui线程上执行与网络相关的操作。 使用thread
或asynctask
。
您将获得蜂窝网络后的NetworkOnMainThreadexception
。
new PostTask().execute();
的AsyncTask
class PostTask extends AsyncTask { @Override protected void doInbackground(Void... params) { // network related operation // do not update ui here // your http post here } }
此外,如果您使用threads
或asynctask
请记住不要在doInbackgroud
更新ui。
你有这个
String msg = msgTextField.getText().toString(); // you can pass msg to asynctask doInbackground or to the asynctask contructor msgTextField.setText("");
使用onPreExecute
和onPostExecute
进行ui更新。
听起来你正在获得NetworkOnMainThread
Exception
原因:您正在Network Operation on Main UI Thread
执行Network Operation on Main UI Thread
解决方案:使用AsyncTask