我是Android开发的新手。我正在尝试一个基本的应用程序。我的要求是我需要将数据从Android应用程序中的文本框发送到使用POST方法在网络上托管的PHP页面。我浏览了很多网站以获得有关此方法的教程,但没找到合适的方法。任何人都可以请给我一个示例代码,使用post方法将数据从Android应用程序中的一个文本框发送到PHP页面?提前谢谢。
答案 0 :(得分: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();
}
}