【问题标题】:How to send data from android to php如何将数据从android发送到php
【发布时间】:2015-07-03 06:33:03
【问题描述】:
【问题讨论】:
-
-
-
看看这个tutorial。它提供了带有android 和php 代码的简单示例,用于传输数据。
-
标签:
java
php
android
json
【解决方案1】:
您应该尝试在 Android 端使用 Asynctask。然后你的 AsyncTask 应该调用一个 PHP 网络服务,它就像一个表单已经发布到被询问的页面。这可以通过使用带有 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" />
希望对你有帮助
【解决方案2】:
// 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:删除插入代码下的空格。