2017-02-11 65 views
9

我想在Android設備上創建http代理服務器。當我嘗試從HTTP服務器(example1.com)讀取響應(example1.com包含內容長度在標頭) 如果HTTP服務器包含內容長度,然後我從內容長度 讀取字節,否則我讀取全部響應如何通過套接字讀取HTTP響應?

byte[] bytes = IOUtils.toByteArray(inFromServer);

問題的字節是,當響應包含content-length響應 快速讀取。 如果響應不包含content-length,則響應緩慢讀取。

這是我的代碼

DataInputStream in = new DataInputStream(inFromServer); 
     //BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     String line = ""; 
     String str = ""; 
     Integer len = 0; 
     while(true) { 
      line = in.readLine(); 
      if (line.indexOf("Content-Length") != -1) 
      { 
       len = Integer.parseInt(line.split("\\D+")[1]); 
       //System.out.println("LINEE="+len); 
      } 

      out.println(line); 
      str = str + line + '\n'; 
      if(line.isEmpty()) break; 
     } 
     int i = Integer.valueOf(len); 
     String body= ""; 
     System.out.println("i="+i); 
     if (i>0) { 
      byte[] buf = new byte[i]; 
      in.readFully(buf); 
      out.write(buf); 
      for (byte b:buf) { 
       body = body + (char)b; 
      } 

     }else{ 

      byte[] bytes = IOUtils.toByteArray(inFromServer); 
      out.write(bytes); 
     } 

出來 - outStream到瀏覽器

+0

你爲什麼不使用更高級別的HTTP庫? –

+0

我正在研究http協議 – Petr

+0

好的,你的問題是當沒有標題時有0個內容需要讀取,所以它會變慢,因爲它讀取整個響應? –

回答

6

首先,你應該知道的http protocal以及它是如何工作的。

和每個HTTP請求,如:

  • 請求行
  • 請求頭
  • 空行
  • 請求體。

,並像所有的HTTP響應:

  • 狀態行
  • 響應頭
  • 空行
  • 響應體。

但是我們可以從http服務器讀取InputStream,我們可以將從inputstream結尾讀取的每一行與'/ r/n'分開。

和你的代碼:

while(true) { 
    **line = in.readLine();** 
    if (line.indexOf("Content-Length") != -1) 
    { 
     len = Integer.parseInt(line.split("\\D+")[1]); 
      //System.out.println("LINEE="+len); 
     } 

     out.println(line); 
     str = str + line + '\n'; 
     if(line.isEmpty()) break; 
    } 
} 

in.readLine()返回的每一行不是以 '/ R/N' 結尾,它返回符合 '/ R' 或「結束/ n'。 也許從這裏的輸入流塊讀取。

這裏是一個IOStreamUtils讀取以'/ r/n'結尾的行。

https://github.com/mayubao/KuaiChuan/blob/master/app/src/main/java/io/github/mayubao/kuaichuan/micro_server/IOStreamUtils.java

7

試試下面的代碼:

// Get server response 
int responseCode = connection.getResponseCode(); 
if (responseCode == 200) { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    String line; 
    StringBuilder builder = new StringBuilder(); 
    while ((line = reader.readLine()) != null) { 
     builder.append(line); 
    } 
    String response = builder.toString() 
    // Handle response... 
} 
+0

在上面的代碼中增加:代碼應該處理異常。在最大情況下,如果響應代碼是200,則響應流可能爲空。 –

相關問題