【问题标题】:How to read an echo statement from Android如何从 Android 读取 echo 语句
【发布时间】:2015-12-08 01:10:30
【问题描述】:

目前我只能实际读取包含 json 格式的 php 文件。

我想要做的是读取一个回显语句(json 格式)来代替读取实际文件。

到目前为止,这是我的 android 代码,用于请求包含 json 格式的 php 文件供我阅读:

// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent(); // This is storing the contents from the php file

提前致谢

这是php文件:

{
"user": [
{
"id": "001",
"name": "Raj Amal",
"email": "raj.amalw@gmail.com"
}
]
}

I want to do this:


<?php
    echo '{
    "user": [
    {
    "id": "001",
    "name": "Raj Amal",
    "email": "raj.amalw@gmail.com"
    }
    ]
    }';
    ?>

【问题讨论】:

  • 我不太清楚你在问什么 - 你得到的回应是什么,你为什么看不懂?需要解析 JSON 什么的吗?

标签: java php android json


【解决方案1】:

尝试如下,

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);

现在可以在httpResponse 中找到来自服务器的响应。您可以将其转换为如下所示的字符串。

String myResponseString = EntityUtils.toString(httpResponse.getEntity());

记录字符串 myResponseString 以查看服务器的响应

【讨论】:

  • @Web.11,更新了我的答案。 response 应该是 httpResponse
【解决方案2】:

我认为您的问题与服务器配置有关。含义 - 服务器将普通 php(即 json)识别为 json 并返回适当的标头。 而您的回声以纯文本形式返回,而没有 HttpEntity 的标头(已弃用!)。

在客户端,上面使用 HttpClient 的答案是可行的方法。

在服务器端:

<?PHP
$data = /** put your content here! **/;
header('Content-Type: application/json');
echo json_encode($data); 

https://stackoverflow.com/a/4064468/324482

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-20
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 2015-08-30
    • 2011-03-31
    相关资源
    最近更新 更多