如何使用Android应用程序将数据发送到网站

Tik*_*aka 5 post android http send

我正在尝试将一些数据发送到我的网站.单击该按钮时,需要将数据发送到网站

但是当我运行程序时,我遇到了一些错误

当我点击按钮时,此消息显示"不幸的是app已经停止",然后退出我的应用程序.

 public class testInput extends Activity {

Button Setbutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);


    setContentView(R.layout.test_input_page);

    Setbutton=(Button)findViewById(R.id.setbtn);

Setbutton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        testInput ti=new testInput();
            //Create the intent



           ti.postData("Sent Data");


    });

}

public void postData(String toPost) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://mysite.com/index.php");

    //This is the data to send
    String MyName = toPost; //any data to send

    try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("action", MyName));

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String response = httpclient.execute(httppost, responseHandler);

    //This is the response from a php application
    String reverseString = response;
    Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();

    } catch (ClientProtocolException e) {
    Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
    // TODO Auto-generated catch block
    } catch (IOException e) {
    Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
    // TODO Auto-generated catch block
    }

    }//end postData()
Run Code Online (Sandbox Code Playgroud)

这是我的PHP代码.

<?php

//code to reverse the string

$reversed = strrev($_POST["action"]);

echo $reversed;

?>
Run Code Online (Sandbox Code Playgroud)

我也获得了在我的应用中使用互联网的许可.

htt*_*tch 3

从 Android 3.x 开始,您无法在主线程中执行网络操作。您需要使用 AsyncTask 或单独的线程,您可以在其中调用 postData 方法。

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html