我正在尝试在
Android设备上创建http代理服务器.当我尝试从HTTP服务器(example1.com)读取响应(example1.com包含头文件中的content-length)
如果HTTP服务器包含content-length,那么我将从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); }
out-outStream到浏览器
解决方法
尝试以下代码:
// 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... }