我想在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到浏览器
你为什么不使用更高级别的HTTP库? –
我正在研究http协议 – Petr
好的,你的问题是当没有标题时有0个内容需要读取,所以它会变慢,因为它读取整个响应? –