2

我是android开发的新手。我正在尝试一个基本的应用程序。我的要求是我需要将数据从 android 应用程序中的文本框发送到使用 POST 方法托管在网络上的 PHP 页面。我浏览了许多网站以获取有关此方法的教程,但没有找到合适的。谁能提供一个示例代码,用于使用 post 方法将数据从 android 应用程序中的一个文本框发送到 PHP 页面?先感谢您。

4

1 回答 1

4

像这样的东西:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText input = (EditText)findViewById(R.id.yourinput);
    input.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String text = input.getText().toString();
            new UploadTask().execute(text);
        }
    });
}

private class UploadTask extends AsyncTask<String, Integer, String> {

    private ProgressDialog progressDialog;
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Uploading...");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://yourwebsite.com/commit.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs
                    .add(new BasicNameValuePair("username", params[0]));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            if (response != null) {
                InputStream in = response.getEntity().getContent();
                String responseContent = inputStreamToString(in);

                return responseContent;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        // process the result
        super.onPostExecute(result);
    }

    private String inputStreamToString(InputStream is) throws IOException {
        String line = "";
        StringBuilder total = new StringBuilder();

        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        // Read response until the end
        while ((line = rd.readLine()) != null) { 
            total.append(line); 
        }

        // Return full string
        return total.toString();
    }
}
于 2013-11-01T12:58:22.217 回答