如何在Android中使用RPC以json格式从服务器(PHP)获取数据
我是安卓新手。我正在尝试创建一个 RPC 来从 PHP 获取数据并获取 JSON 格式。一切顺利,但我没有收到任何数据作为响应。下面是我的 android 代码
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);
}
}
?>
如果我在这里做了什么,请告诉我
I am new in Android. I am trying to make an RPC
to fetch data from PHP
and get in JSON
format. Everything goes fine but I am not getting any data as response. Bellow is my android code
Android Code
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 Code
<?php
class TestJava
{
public function getData()
{
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
}
}
?>
Please let me know if anything I did here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您滥用了实体元素。检查我的代码中有什么:
I think you misused entity element. Check what I have in my code:
我有点惊讶你如何从这个 php 脚本中检索任何信息。该脚本不输出任何内容。尝试这样:
第二个“奇怪”的事情是您在应用程序中接收数据的方式。你应该读取输入流而不是写入输出流......或者我完全错过了什么?!
I am a little surprised how you could retrieve any information from this php script. This script doesnt output anything. Try it like this:
The second "strange" thing is your way of receiving data in your app. You should read a input stream instead of writing into a output stream... Or did I completely miss something?!