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

标签 android http post send

我正在尝试向我的网站发送一些数据。单击按钮时,需要向网站发送数据

但是我在运行程序的时候出现了一些错误

当我点击按钮时,出现“不幸的是应用程序已停止”的消息,然后退出我的应用程序。

 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()

这是我的 PHP 代码。

<?php

//code to reverse the string

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

echo $reversed;

?>

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

最佳答案

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

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

关于android - 如何使用android应用程序将数据发送到网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16315415/

相关文章:

android - 将 Android Studio 项目和配置从 Windows 7 移动到 OS X

android Activity 的弱引用

java - @override 在 android 中使用 onDraw 导致错误

javascript - 在成功登录后运行 HTTP post

javascript - Node : Display POST data from another website

android - Async 是否执行 block ui 线程?

javascript - 使用 Javascript 和 C# 连接服务器和客户端

java - https4 端点是什么意思?这和https有区别吗?

php - POST 数据加密 - HTTPS 就足够了吗?

database - ElasticSearch 异步发布