栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何存储可能包含二进制数据的Http响应?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何存储可能包含二进制数据的Http响应?

将其存储在字节数组中:

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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508736.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号