我正在尝试在安卓设备上创建http代理服务器。当我试图从HTTP服务器(example1.com)读取响应时(example1.com在头部包含 content-length),如果HTTP服务器包含content-length,则我会读取来自content-length的字节,否则我会读取响应的全部字节。
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);
}
输出 - 将数据流发送到浏览器