所以我正在编写一个Android应用程序,其中一部分应该使用GPS来获取经度/纬度。这些值应该发布到我也正在运行的PHP服务器。我发布的功能如下:
public void doAll() {
Double locLat, locLon;
try {
locLat = locManager.getLastKnownLocation(locProvider).getLatitude();
locLon = locManager.getLastKnownLocation(locProvider).getLongitude();
} catch (NullPointerException e) {
locLat = -1.0;
locLon = -1.0;
}
try {
HttpClient client = new DefaultHttpClient();
//we put all the parameters in the URL itself
HttpPost request = new HttpPost("http://fatalatour.com/database.php?function=get_all&latitude="+Double.toString(locLat)+"&longitude="+Double.toString(locLon));
ResponseHandler <String> responseHandler = new BasicResponseHandler();
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//nameValuePairs.add(new BasicNameValuePair("latitude", Double.toString(locLat)));
//nameValuePairs.add(new BasicNameValuePair("longitude", Double.toString(locLon)));
//request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = client.execute(request, responseHandler);
Log.i("HOMI_RESPONSE", response.toString());
}
还有其他代码,但我相信这就是实际影响 locLat 和 locLon 发布的全部内容。
对于服务器端,我有:
function get_all() {
$lat = trim($_GET['latitude']);
$lon = trim($_GET['longitude']);
// DEBUG
$f = fopen('debug.log', 'a');
fprintf($f, 'get_all: '.print_r($_REQUEST, true)."'n");
$result = mysql_query("SELECT * FROM homi_table");
$num = 0; //# of homicides
while ($row = mysql_fetch_assoc($result)) {
$d = distance($row['latitude'], $row['longitude'], $lat, $lon, "K");
if ($d < 100) { //number to change for distance filter
$num += 1;
echo "fatality:".$row['slug']."~".strtoupper($row['name']).", Age ".$row['age']."'n".$row['date']."'nhttp://projects.latimes.com/homicide/post/".$row['slug']."~".$row['latitude']."~".$row['longitude'];
// GH: limiting the number of results to 100
if ($num == 100) {
break;
}
}
};
echo $num;
fprintf($f, "get_all: returning: ".$num."'n");
}
现在的问题似乎是如何处理$lat和$lon。当我为 PHP 中的每个应用程序硬编码静态数字时,该应用程序可以工作,但是当我将其保留为变量(应该是)时,它会失败。任何帮助将不胜感激!
在Android应用程序中,您使用的是POST请求,在PHP中,您读取GET参数。我没有想到别的。
您构建的 URL 看起来像 HTTP Get,而不是 Post。 Post 会将数据发布在请求正文中。
如果你不介意URL中暴露的参数,我会简单地在Android代码中将HTTPPost更改为HTTPGet。如果你不希望这些东西出现在URL中,你将不得不稍微修改一下Android帖子(我相信类似于你注释掉的代码),并更改php代码以访问$_POST变量。