我是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
class TestJava
{
public function getData()
{
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
}
}
?>
如果我在这里做了什么,请告诉我
答案 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);
?>
第二个“奇怪”的事情是您在应用中接收数据的方式。您应该读取输入流而不是写入输出流......或者我完全错过了什么?!