【问题标题】:How to fetch data from server (PHP) using RPC in json format in Android如何在 Android 中使用 RPC 以 json 格式从服务器 (PHP) 获取数据
【发布时间】:2011-09-18 14:45:21
【问题描述】:

我是 Android 新手。我正在尝试制作一个RPC 以从PHP 获取数据并获取JSON 格式。一切都很好,但我没有得到任何数据作为响应。贝娄是我的安卓代码

安卓代码

try{
    HttpClient httpClient = new DefaultHttpClient();


    JSONObject jsonRequest = new JSONObject(); 
    jsonRequest.put("id", 0); 
    jsonRequest.put("method", "getData"); 


    HttpEntity entity = new StringEntity(jsonRequest.toString()); 
    HttpPost request = new HttpPost("http://121.247.130.30:8080/test/TestJava.php");
    request.setEntity(entity); 
    HttpResponse response = httpClient.execute(request); 
    String temp = EntityUtils.toString(response.getEntity());
    Log.e("Class====","Error:"+temp);
   }
   catch(Exception e){
       Log.e("Class====","Error:"+e.getMessage());
   }

PHP 代码

<?php
class TestJava
{
public function getData()  
{  
   $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
   echo json_encode($arr);
} 
}
?>

如果我在这里做了什么,请告诉我

【问题讨论】:

    标签: android json rpc


    【解决方案1】:

    我认为您滥用了实体元素。检查我的代码中的内容:

    StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode() == HttpStatus.SC_OK){ ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); response.getEntity().consumeContent(); out.close(); 返回 out.toString(); }

    【讨论】:

    • 感谢您的回答。我已经编写了您的代码 sn-p,现在得到了 200 个响应代码,但问题是 BytearrayOutputStream 对象包含空白数据。对象的('out' here)错误就像 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]。最后我每次都会收到这个错误-java.lang.IllegalStateException: Content has been used。我哪里做错了?
    • 我已经用退货编辑了我的答案。我看不出你做错了什么。在我的代码中,这是在 httpclient.execute(...
    【解决方案2】:

    我有点惊讶您如何从这个 php 脚本中检索任何信息。该脚本不输出任何内容。试试这样:

    <?php
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
    echo json_encode($arr);
    ?>
    

    第二个“奇怪”的事情是您在应用中接收数据的方式。您应该读取输入流而不是写入输出流......还是我完全错过了什么?!

    【讨论】:

    • 是的,马可。我的问题不在于 php 脚本,实际上我的问题是我正在寻找一种解决方案,在该解决方案中,我将拥有一个类来建立与 php 类的连接桥,并使用该连接我可以访问该类的方法/过程我可以管理结果处理程序或故障处理程序。
    猜你喜欢
    • 2014-09-26
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    相关资源
    最近更新 更多