2013-07-04 37 views
4

我使用httpclient的apache httpcompnonents庫。我想在一個多線程的應用程序中使用它,在這個應用程序中線程的數量將非常高,並且會有頻繁的http調用。這是我用來在執行調用後讀取響應的代碼。apache httpclient-讀取響應的最有效方式

HttpEntity entity = httpResponse.getEntity(); 
String response = EntityUtils.toString(entity); 

我只是想確認它是讀取響應的最有效方式嗎?

謝謝, 與Hemant

回答

13

這實際上表示處理HTTP響應的最低效方式。

您很可能想要將響應的內容消化到排序的域對象中。那麼,以字符串的形式在內存中緩衝它的意義是什麼?

處理響應處理的推薦方式是使用自定義ResponseHandler,它可以通過直接從底層連接流式傳輸內容來處理內容。使用ResponseHandler的附加好處是它完全免除了處理連接釋放和資源釋放的麻煩。

編輯:修改示例代碼使用JSON

下面是使用的HttpClient 4.2和Jackson JSON處理器它的一個例子。假設Stuff是您的具有JSON綁定的域對象。

ResponseHandler<Stuff> rh = new ResponseHandler<Stuff>() { 

    @Override 
    public Stuff handleResponse(
      final HttpResponse response) throws IOException { 
     StatusLine statusLine = response.getStatusLine(); 
     HttpEntity entity = response.getEntity(); 
     if (statusLine.getStatusCode() >= 300) { 
      throw new HttpResponseException(
        statusLine.getStatusCode(), 
        statusLine.getReasonPhrase()); 
     } 
     if (entity == null) { 
      throw new ClientProtocolException("Response contains no content"); 
     } 
     JsonFactory jsonf = new JsonFactory(); 
     InputStream instream = entity.getContent(); 
     // try - finally is not strictly necessary here 
     // but is a good practice 
     try { 
      JsonParser jsonParser = jsonf.createParser(instream); 
      // Use the parser to deserialize the object from the content stream 
      return stuff; 
     } finally { 
      instream.close(); 
     } 
    } 
}; 
DefaultHttpClient client = new DefaultHttpClient(); 
Stuff mystuff = client.execute(new HttpGet("http://somehost/stuff"), rh); 
+0

感謝oleg,聽取您的建議我現在已經使用了響應處理程序。但是我需要響應字符串來通過結果,使用EntityUtils.toString(實體)是有效的;在響應處理程序中? – Hemant

+0

@Hemant:你錯過了我想要得到的最重要的一點:無論你如何做,它都會將HTTP消息內容轉換爲String。 – oleg

+0

我的恐懼成真......但我需要將此字符串轉換爲jsonObject,因爲此服務返回json字符串......現在如何轉換爲jsonobject而不將其轉換爲字符串? – Hemant

相關問題