我想在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個內容需要讀取,所以它會變慢,因爲它讀取整個響應? –