如何在Android中使用json格式的RPC从服务器(PHP)获取数据

时间:2011-06-20 11:17:31

标签: android json rpc

我是Android新手。我正在尝试RPCPHP获取数据并获得JSON格式。一切都很顺利,但我没有得到任何数据作为回应。贝娄是我的安卓代码

Android代码

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);
} 
}
?>

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

2 个答案:

答案 0 :(得分:1)

我认为你误用了实体元素。检查我的代码中包含的内容:

StatusLine statusLine = response.getStatusLine();

if(statusLine.getStatusCode() == HttpStatus.SC_OK ){

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    response.getEntity().writeTo(out);
    response.getEntity().consumeContent();
    out.close();
    return out.toString();

}

答案 1 :(得分:0)

我有点惊讶你如何从这个PHP脚本中检索任何信息。这个脚本不输出任何东西。试试这样:

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

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