2015-12-08 18 views
-1

目前我只能夠實際讀取包含json格式的php文件。如何從Android中讀取回聲聲明

我想要做的是閱讀的回聲聲明(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": "[email protected]" 
} 
] 
} 

I want to do this: 


<?php 
    echo '{ 
    "user": [ 
    { 
    "id": "001", 
    "name": "Raj Amal", 
    "email": "[email protected]" 
    } 
    ] 
    }'; 
    ?> 
+0

這不是很清楚,我你的要求 - 什麼是你所得到的迴應,爲什麼不能你看了嗎?你需要解析JSON還是什麼? – ajshort

回答

1

試試如下,

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

現在,服務器的響應將在httpResponse中找到。你可以將它轉換爲如下所示的字符串。

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

登錄串myResponseString看你從服務器

+0

無法解析符號「響應」 –

+1

@ Web.11,更新了我的答案。 'response'應該是'httpResponse'。 – codePG

0

迴應,我覺得你的問題是與服務器配置。含義 - 簡單的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