我是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应用程序,以下是我正在使用的代码:
JAVA:
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';
}
?>
由于我是新手,我想知道我做的事情是否正确。
答案 0 :(得分:1)
您的代码在PHP方面是一团糟。你不能只是回应事物。这将导致JSON解析失败。
我建议您使用Google自己的轻量级GSON library。您使用POJO类来解析json。一旦你有了GSON的POJO课程,你所要做的就是使用HttpResponse
中的HttpPost
来阅读答案本身,如下所示:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
try {
List<NameValuePair> values = new ArrayList<NameValuePair>(2);
values.add(new BasicNameValuePair("id", "12345"));
values.add(new BasicNameValuePair("message", "asdf");
post.setEntity(new UrlEncodedFormEntity(values));
HttpResponse httpresponse = client.execute(post);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
Gson gson = new Gson();
Reader reader = new InputStreamReader(stream);
Response finishresponse = gson.fromJson(reader, Response.class);
return finishresponse;
} catch (Exception e) {
e.printStackTrace();
}
return null;
就我而言,我的POJO类是我创建的Response
类。