2

我是 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';
}


    ?>

因为我是新手,所以我也想知道我做的事情是否正确。

4

1 回答 1

1

您的代码在 PHP 方面是一团糟。你不能只是回声。这将导致 JSON 解析失败。

我建议您使用 Google self 的轻量级GSON 库。您使用 POJO 类来解析 json。一旦你有了一个带有 GSON 的 POJO 类,你所要做的就是使用HttpResponsefrom yourHttpPost来读取响应本身,如下所示:

        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我创建的类。

于 2013-03-18T11:29:45.297 回答