我想从 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 是否收到请求。
在模拟器上测试:本地主机是指运行代码的设备,如果与模拟器有关,则必须使用IP地址10.0.2.2
.
在设备上测试:如果您要在物理设备上测试应用程序,则必须打开 USB 网络共享,然后检查设备和电脑之间关联的 IP 地址。 (移动数据打开或关闭都没有关系)
在Linux中,您可以使用sudo ipconfig
检查该IP地址
它将打开所有网络接口(interface),您必须从这些接口(interface)中找到带有 usn0
或类似名称的接口(interface)。
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);
?>
关于php - 从 Android 到 PHP 后端的 HTTP Post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20257198/