2011-02-16 75 views
4

我用下面的代碼進行HTTP連接:如何從HttpResponse中讀取一個bytearray?

HttpClient client = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost(url); 
HttpResponse response = client.execute(httpPost); 

我想讀從響應對象的ByteArray。

我該怎麼做?

+0

請回滾。 - 對。 :) – Kriem 2011-02-16 11:07:42

回答

0

我做了一些非常類似於此的事情,但它是一段時間以前。

看着我的源代碼我用

HttpClient client = new DefaultHttpClient(); 
String url = "http://192.168.1.69:8888/sdroidmarshal"; 
HttpGet getRequest = new HttpGet(url); 

ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
String proto = client.execute(getRequest, responseHandler); 

我敢肯定的是,對ResponseHandler的關鍵是這個。我的get請求只是簡單地返回了我需要的字符串。

在字節組的情況下,你可能會想使用一個InputStream像這樣

ResponseHandler<InputStream> responseHandler = new BasicResponseHandler(); 
InputStream in = client.execute(getRequest, responseHandler); 

其經過短短處理的InputStream爲正常。

有點谷歌搜索建議您可能還需要使用HttpResponseHandler()而不是BasicResponseHandler(),如我的示例中,我會撥弄。

我的工作的完整源代碼是here,它可能對您有所幫助。

1

您可以使用:

HttpResponse response = client.execute(httpPost); 
String content = EntityUtils.toString(response.getEntity()); 
byte[] bytes = content.getBytes("UTF8"); 

你可以用一個適當的響應替換的字符編碼。

+0

非常危險的建議。你可以得到損壞的字節不匹配最初回應的服務器。首先將數據解碼爲Unicode字符串(可能帶有錯誤/損壞),然後編碼爲UTF-8,這可能不是原始響應中使用的編碼 – Alfishe 2014-03-18 01:19:42

5

可以用該方法直接讀取字節數組:EntityUtils.toByteArray

HttpClient client = new DefaultHttpClient(); 
HttpGet get = new HttpGet("localhost:8080/myurl"); 
HttpResponse response = client.execute(get); 
byte[] content = EntityUtils.toByteArray(response.getEntity());