2011-08-05 65 views
13

好的,我已經成功地連接到遠程服務器,並接收響應HTTP/1.1 200 OK和響應被打包到HttpResponse對象。現在我如何從響應中獲取響應中的數據,特別是從服務器發送的JSON?提取消息主體出來的HttpResponse

回答

24

是這樣的:重複此:How do I parse JSON from a Java HTTPResponse?

HttpResponse response; // some response object 
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
String json = reader.readLine(); 
JSONTokener tokener = new JSONTokener(json); 
JSONArray finalResult = new JSONArray(tokener); 
4

那麼,你可以通過調用getEntity()得到HttpResponse的主體,它返回HttpEntity類型的對象。那麼你將要消耗的是從HttpEntitygetContent()方法返回的InputStream。我會做這樣的:

public static String entityToString(HttpEntity entity) { 
    InputStream is = entity.getContent(); 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder str = new StringBuilder(); 

    String line = null; 
    try { 
    while ((line = bufferedReader.readLine()) != null) { 
     str.append(line + "\n"); 
    } 
    } catch (IOException e) { 
    throw new RuntimeException(e); 
    } finally { 
    try { 
     is.close(); 
    } catch (IOException e) { 
     //tough luck... 
    } 
    } 
    return str.toString(); 
} 
0

調用httpclient.execute()

ResponseHandler <String> resonseHandler = new BasicResponseHandler(); 
String response = httpclient.execute(httpget, resonseHandler); 
1

你也可以使用時,請使用BasicResponseHandler EntityUtils

response = cl.execute(p); //cl is http client and p is the post request 

if(response.getStatusLine().getStatusCode()==200) 
{ 
    try 
    { 
     String resp_body = EntityUtils.toString(response.getEntity()); 
     Log.v("resp_body", resp_body.toString()); 
     JSONObject jsobj = new JSONObject(resp_body); 
    } 
    catch(Exception e) 
    { 

     Log.e("sometag",e.getMessage()); 
    } 
} 

PS:您可能不得不這樣做在一個單獨的線程,除了主線程,就像在主線程異常的的AsyncTask或網絡運行可能出現的doInBackground()。

相關問題