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

如何使用Java套接字HTTP / 1.1请求下载图像?

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

如何使用Java套接字HTTP / 1.1请求下载图像?

使用

BufferedReader
有误,原因有两个:

  1. 它将字节转换为
    String
    ,然后再转换回字节以将其发送到输出流。转换可能(可能会)导致数据丢失;
  2. 它解析了太多字节,您无法控制它。

您需要通过手术来解决此问题,创建一个所需大小的字节缓冲区,并使用an

InputStream
根据自己的条件逐字节读取流。另外,由于您知道HTTP标头的结尾为“ r n r n”(或13 10 13
10字节),因此可以扫描自己的缓冲区以查找此模式并采取相应的措施。

最好的选择是将图像下载到文件中,然后使用ImageIO从本地文件中读取图像。

这是允许您通过剪切标题下载图像文件(或任何其他文件)的代码:

    // Initialize the streams.    final FileOutputStream fileOutputStream = new FileOutputStream(file);    final InputStream inputStream = socket.getInputStream();    // Header end flag.    boolean headerEnded = false;    byte[] bytes = new byte[2048];    int length;    while ((length = inputStream.read(bytes)) != -1) {        // If the end of the header had already been reached, write the bytes to the file as normal.        if (headerEnded) fileOutputStream.write(bytes, 0, length);        // This locates the end of the header by comparing the current byte as well as the next 3 bytes        // with the HTTP header end "rnrn" (which in integer representation would be 13 10 13 10).        // If the end of the header is reached, the flag is set to true and the remaining data in the        // currently buffered byte array is written into the file.        else { for (int i = 0; i < 2045; i++) {     if (bytes[i] == 13 && bytes[i + 1] == 10 && bytes[i + 2] == 13 && bytes[i + 3] == 10) {         headerEnded = true;         fileOutputStream.write(bytes, i+4 , 2048-i-4);         break;     } }        }    }    inputStream.close();    fileOutputStream.close();


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

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

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