2012-04-06 54 views

回答

1

这里是一些示例代码,我从服务器获取JSON。它包括通过HTTP连接到某些东西的基本代码行。

public JSONArray getQuestionsJSONFromUrl(String url, List<NameValuePair> params) { 
    // Making HTTP request 
try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     httpPost.setEntity(new UrlEncodedFormEntity(params)); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     String jsonData = reader.readLine(); 
     JSONArray jarr = new JSONArray(jsonData); 
     is.close(); 
     return jarr; 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 
    return null; 
}