将其存储在字节数组中:
byte[] bufer = new byte[???];
更详细的过程:
- 创建一个足够大的缓冲区以容纳响应头(如果较大,则丢弃异常)。
- 将字节读取到缓冲区,直到
rnrn
在缓冲区中找到为止。您可以编写一个辅助函数,例如static int arrayIndexOf(byte[] haystack, int offset, int length, byte[] needle)
- 当遇到标头的末尾时,在缓冲区的前 n 个字节中创建一个strinform 。然后,您可以在此strng上使用RegEx(还请注意,RegEx不是解析HTTPeaders的最佳方法)。
- 准备使缓冲区在标头之后包含其他数据,这些数据是响应正文的第一个字节。您必须将这些字节复制到输出流或输出文件或输出缓冲区。
- 阅读 其余 的响应正文。(直到读取 content-length 或关闭流)。
编辑:
您没有按照我建议的步骤进行操作。
inputReader.ready()是检测响应阶段的错误方法。无法保证标头将在单个突发中发送。
我试图用代码(arrayIndexOf除外)函数编写原理图。
InputStream is;// Create a buffer large enough for the response header (and drop exception if it is bigger).byte[] headEnd = {13, 10, 13, 10}; // r n r nbyte[] buffer = new byte[10 * 1024];int length = 0;// Read bytes to the buffer until you find `rnrn` in the buffer. int bytes = 0;int pos;while ((pos = arrayIndexOf(buffer, 0, length, headEnd)) == -1 && (bytes = is.read(buffer, length, buffer.length() - length)) > -1) { length += bytes; // buffer is full but have not found end siganture if (length == buffer.length()) throw new RuntimeException("Response header too long");}// pos contains the starting index of the end signature (rnrn) so we add 4 bytespos += 4;// When you encounter the end of header, create a strinform the first *n* bytesString header = new String(buffer, 0, pos);System.out.println(header);// Be prepared that the buffer will contain additional data after the header// ... so we process itSystem.out.write(buffer, pos, length - pos);// process the rest until connection is closedwhile (bytes = is.read(buffer, 0, bufer.length())) { System.out.write(buffer, 0, bytes);}该
arrayIndexOf方法可能看起来像这样:(可能有更快的版本)
public static int arrayIndexOf(byte[] haystack, int offset, int length, byte[] needle) { for (int i=offset; i<offset+length-nedle.length(); i++) { boolean match = false; for (int j=0; j<needle.length(); j++) { match = haystack[i + j] == needle[j]; if (!match) break; } if (match) return i; } return -1;}


