2017-02-11 28 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,则响应流可能为空。 –

相关问题