2011-12-19 81 views
1

我在閱讀URL中的JSON時遇到問題。從Android中讀取JSON內容

對於桌面應用程序,我一直使用「curl」從URL讀取內容。

curl -H 'Accept: application/json' 'http://example.com/abc.py/data'

我使用下面的代碼做Android應用程序相同,但它不工作。

 HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url); 
     httppost.addHeader("Accept", "application/json"); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 

任何人都可以幫忙嗎?

感謝,

+0

什麼是不工作? – 2011-12-19 02:03:16

+0

你想解析你的android應用程序中的JSON嗎? – 2011-12-19 04:04:38

回答

0

有很多原因,可能無法正常工作,一個原因是,它實際上是可以被的getContent返回的inputStream,這裏的工作代碼片段從我的應用程序

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 


... 


private static String getInputStreamAsString(Context ctxt, InputStream is) 
{ 
    byte[] sBuffer = new byte[512]; 
    ByteArrayOutputStream content = new ByteArrayOutputStream(); 

    // Read response into a buffered stream 
    int readBytes = 0; 
    try 
    { 
     while ((readBytes = is.read(sBuffer)) != -1) 
     { 
      content.write(sBuffer, 0, readBytes); 
     } 
    } 
    catch (IOException e) 
    { 
     Util.e(ctxt, TAG, Util.fmt(e)); 
    } 
    return new String(content.toByteArray()); 
} 


public static test() { 
    HttpClient client = DefaultHttpClient() 
    HttpGet request = new HttpGet(url); 
    HttpResponse response = client.execute(request);; 
    StatusLine status = response.getStatusLine(); 
    String str = getInputStreamAsString(ctxt, response.getEntity().getContent()); 
    JSONObject json = new JSONObject(str); 
} 

... 
0

謝謝全部爲您的答覆。

錯誤發生的原因是我沒有在清單中設置Internet權限,因此無法連接到URL。

它現在的作品:)

+0

如果已解決,請關閉此問題;) – Merlin 2011-12-19 16:24:39