我是 PHP 和 Java http 客户端的新手,我正在尝试向我的服务器上的 PHP 脚本发布消息,我尝试了以下示例:http ://webtutsdepot.com/2011/11/15/android-tutorial-how -to-post-data-from-an-android-app-to-a-website/
但是我无法理解如何将 JSON 结果发送回我的 android 应用程序,以下是我正在使用的代码:
爪哇:
public void send(View v)
{
// get the message from the message text box
String msg = Et.getText().toString();
// make sure the fields are not empty
if (msg.length()>0)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://animsinc.com/query.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
Et.setText(""); // clear text box
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
PHP:
<?php
require 'phtry.php';
$message = $_POST["message"];
$query = "SELECT `surname`,`firstname` FROM `users`";
$query1 = "SELECT * FROM `users` WHERE id = $message";
if ($query_run = mysql_query($query1)){
//echo 'Success.';
while ($query_row = mysql_fetch_assoc($query_run)){
$surname = $query_row['surname'];
$firstname = $query_row['firstname'];
}
$out [] = $query_row;
print(json_encode($out)); // If I check with my web browser I get a [false] display here
}else{
echo 'No Success';
}
?>
因为我是新手,所以我也想知道我做的事情是否正确。