2011-12-19 79 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