我想从Android到后端服务器进行HTTP Post,该服务器将运行PHP脚本来接收这些数据并将内容保存到文本文件中。
对于Android HTTP Post,我遵循的示例可以在http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
但是,我找不到任何关于后端PHP部分的参考。最接近的是PHP上传方法http://www.php.net/manual/en/features.file-upload.post-method.php但它是用于文件上传的。
在SO Get Data Sent by HttpPost in Java to php Script中有一篇旧帖子,但也没有答案。
你知道我该怎么做吗?基本上,我想从Android接收发布的数据,并将内容保存到文本文件中。
首先要确保你的script.php是否收到请求。
在模拟器上测试:localhost指的是运行代码的设备。如果是关于模拟器的,则必须使用IP address 10.0.2.2
。
在设备上测试:如果你在物理设备上测试你的应用程序,那么你必须打开USB Tethering,然后检查你的设备和电脑之间的ip地址。(无论移动数据是打开还是关闭)
在Linux中,您可以使用sudo ipconfig
检查该IP地址
它将o/p所有网络接口,从那些你必须找到的usn0
或类似的接口。
usb0 Link encap:Ethernet HWaddr 06:94:c7:0d:51:43
inet addr:192.168.42.106 Bcast:192.168.42.255 Mask:255.255.255.0
inet6 addr: fe80::494:c7ff:fe0d:5143/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:21 errors:0 dropped:0 overruns:0 frame:0
TX packets:29 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:2016 (1.9 KiB) TX bytes:3978 (3.8 KiB)
在这里你可以看到设备IP是192.168.42.106所以,在Android中你应该使用类似的URL
http://192.168.42.106/script.php
在windows中,它有类似的命令ipconfig
。
Android源
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.42.106/script.php"); // <-- for Device, and for emulator--> http://10.0.2.2/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
}
}
在Android代码中设置正确的IP后,读取script.php
中的POST参数,并创建一个新文件来存储该数据:
<?php
//getting data from POST request.
$arg1= $POST['id'];
$arg2= $POST['stringdata'];
//creating file
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't create file");
//wrinting content to file
fwrite($ourFileHandle, $arg1);
fwrite($ourFileHandle, $arg2);
//closing file
fclose($ourFileHandle);
?>
您看过file_put_contents
吗?http://us1.php.net/file_put_contents
您可以获取POST请求字符串并将其写入文件。
如果字符串太大,您可能不得不用fwrite
之类的东西对其进行分块(http://us1.php.net/manual/en/function.fwrite.php)
这是单据
you should refer localhost as : 10.0.2.2
In your case u should change to 10.0.2.2/scipt.php