我正在尝试从Android应用程序向PHP脚本发送一些POST数据。 PHP脚本应该如何?这是我尝试过的,但它不起作用;
Android代码:
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.alex26.0fees.net/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
@Override
protected void onPostExecute(String result) {
}
}
PHP脚本:
<?php
if(isset($_POST['id']))
echo $_POST['id'];
if(isset($_POST['stringdata']))
echo $_POST['stringdata'];
?>
答案 0 :(得分:2)
通过POST发送到PHP脚本的任何内容都以$_POST
数组结尾。脚本将用它做什么是另一个问题。最简单的测试,将$ _POST的内容写入名为“myfile.txt”的文件中(注意每个请求都会覆盖文件的内容):
<?php
file_put_contents("myfile.txt", print_r( $_POST, true ));
?>
在你的脚本中回显是毫无意义的 - 你没有消耗服务器响应也没有显示它,所以它怎么能“工作”?