這實際上表示處理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);
感謝oleg,聽取您的建議我現在已經使用了響應處理程序。但是我需要響應字符串來通過結果,使用EntityUtils.toString(實體)是有效的;在響應處理程序中? – Hemant
@Hemant:你錯過了我想要得到的最重要的一點:無論你如何做,它都會將HTTP消息內容轉換爲String。 – oleg
我的恐懼成真......但我需要將此字符串轉換爲jsonObject,因爲此服務返回json字符串......現在如何轉換爲jsonobject而不將其轉換爲字符串? – Hemant