问题描述
我想一些POST数据从一个Android应用程序发送到PHP脚本。 PHP脚本应该怎么样子?这是我试过,但它不工作;
Android的code:
类SendPostReqAsyncTask扩展的AsyncTask<弦乐,太虚,字符串> {
@覆盖
保护字符串doInBackground(字符串... PARAMS){ //创建一个新的HttpClient和邮政头
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httppost =新HttpPost(http://www.alex26.0fees.net/script.php); 尝试{
//添加数据
清单<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);
nameValuePairs.add(新BasicNameValuePair(ID,12345));
nameValuePairs.add(新BasicNameValuePair(StringData是,AndDev是太酷了!));
httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中)); //执行HTTP POST请求
HTT presponse响应= httpclient.execute(httppost); }赶上(ClientProtocolException E){
// TODO自动生成catch块
}赶上(IOException异常五){
// TODO自动生成catch块
}
返回null;
} @覆盖
保护无效onPostExecute(字符串结果){ }
}
PHP脚本:
< PHP
如果(使用isset($ _ POST ['身份证']))
回声$ _ POST ['身份证'];
如果(使用isset($ _ POST ['StringData是']))
回声$ _ POST ['StringData是'];
?>
通过POST发送到PHP脚本中的任何 $ _ POST
数组结束。什么脚本会用它做是另外一个问题。简单的测试,写入的$ _ POST内容到一个名为myfile.txt的(注:每个请求将覆盖该文件的内容)文件:
< PHP 的file_put_contents(myfile.txt的的print_r($ _ POST,真实));?>
在你的脚本呼应是没有意义的 - 你是不是消耗服务器的响应,也不显示它怎么可能是工作
I'm trying to send some POST data to a PHP script from an android application. How should the PHP script look like? This is what I tried but it doesn't work;
Android code:
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 script:
<?php
if(isset($_POST['id']))
echo $_POST['id'];
if(isset($_POST['stringdata']))
echo $_POST['stringdata'];
?>
Anything sent via POST to PHP script ends in $_POST
array. What the script will do with it is another question. Simplest test, that writes content of $_POST to a file named "myfile.txt" (note each request would overwrite content of the file):
<?php
file_put_contents("myfile.txt", print_r( $_POST, true ));
?>
echoing in your script is pointless - you are not consuming server response nor displaying it so how could it "work"?
这篇关于从Android应用程序到PHP脚本发送POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!