2014-11-04 62 views
0

我有一臺服務器和一個客戶端。我的服務器以文本格式發送HttpResponse。我能夠在客戶端收到文本。我需要將文本轉換回HttpResponse對象。是否有任何開源庫或內置的java/Android機制來做到這一點?ByteArray to HttpResponse

我得到的只是將HttpResponse轉換爲文本。

+0

你怎麼收到的ByteArray? – 2014-11-04 08:33:24

+0

使用recv系統調用。 – Kishore 2014-11-04 08:38:13

+0

'我的服務器在byteArray'中發送一個HttpResponse。 http服務器是一個http服務器,因此只會發送文本,圖片或文檔。它總是一個字節流。所以我想知道你是什麼意思的響應作爲字節數組。 – greenapps 2014-11-04 09:50:04

回答

0

嘗試這種方式

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
response.getEntity().writeTo(baos); 
byte[] bytes = baos.getBytes(); 

然後可以按如下的內容添加到另一個HttpResponse對象:

HttpResponse response = httpClient.execute(new HttpGet(URL)); 
response.setEntity(new ByteArrayEntity(bytes)); 
+0

基本上我需要一個HttpParser開源庫。 – Kishore 2014-11-04 08:43:07

0

只是這樣做使用Apache下議院IO:http://commons.apache.org/proper/commons-io/

private byte[] receiveByteArrayData(HttpURLConnection httpURLConnection) 
    throws IOException 
{ 
    return IOUtils.toByteArray(httpURLConnection.getInputStream()); 
} 

發送byte[]數據:

URL url = new URL("http://your.url.here:yourPortNumber/something"); 
    HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(); 
    httpUrlConnection.setDoInput(true); 
    httpUrlConnection.setDoOutput(true); 
    httpUrlConnection.setRequestProperty("Content-Type", "application/octet-stream"); 
    httpUrlConnection.setRequestMethod("POST"); 
    httpUrlConnection.setFixedLengthStreamingMode(bytes.length); 

    httpUrlConnection.connect(); 

    httpUrlConnection.getOutputStream().write(bytes); 
    httpUrlConnection.getOutputStream().flush(); 
    if (httpsUrlConnection.getResponseCode() == 200) //OK 
    { 
     System.out.println("successfully uploaded data"); 
    } 
    httpUrlConnection.disconnect();