如何将数据从android发送到php?
我有类GPSTracker.java这个类来获取当前位置,我想将纬度,经度和地址等位置数据发送到服务器,那么,我该怎么办?
和这个GPSTracker.java http://pastebin.com/0ZVUdC0w
答案 0 :(得分:2)
你应该尝试使用Android方面的Asynctask。然后,您的AsyncTask应该调用PHP Web服务,它就像一个表单已经发布到被询问的页面。这可以通过使用带有nameValuePairs的HttpPost请求来实现(我允许您根据需要安排代码)。然后你可以用服务器端的值做任何你想做的事情
HttpClient client = new DefaultHttpClient();
// Http Request Params Object
HttpPost post = new HttpPost("SERVER_ADRESS/Webservice.php");
// Any other parameters you would like to set
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Key", Value));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
post.setEntity(entity);
// Response from the Http Request
response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
// Check the Http Request for success
if (statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
// Put value returned by the Webservice in content
content = out.toString();
doSomethingWithReturnedValue(content);
}
您可能还需要以下权限
<uses-permission android:name="android.permission.INTERNET" />
希望有所帮助
答案 1 :(得分:0)
// Include config file
include_once('confi.php');
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : "";
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['pwd']) ? mysql_real_escape_string($_POST['pwd']) : "";
$status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";
// Insert data into data base
$sql = "INSERT INTO ` kwd `.` users ` (` I D `, ` n a m e `, ` e m a i l `, ` p a s s word `, `s t a t us`) VALUES (NULL, '$name', '$email', '$password', '$status');";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
@mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
PS:删除插入代码下的空格。