如何将Http url(图像URL)转换为字节缓冲区或字节?

时间:2018-06-25 11:13:23

标签: java arrays url inputstream imageurl

我尝试了一些将URL图像转换为字节缓冲区的功能,但是它不起作用。它显示IOException错误

String imagePath = "https://www.clearias.com/up/UPSC-Civil-Services-Mains-Exam-2018-Timetable-V1.png";

尝试1:

URL u = new URL(imagePath);
int contentLength = u.openConnection().getContentLength();
InputStream openStream = u.openStream();
byte[] binaryData = new byte[contentLength];
openStream.read(binaryData);
ByteBuffer imageBytes = ByteBuffer.wrap(openStream);

当我将openStream包装到ByteBuffer时,这会显示错误

  

“ ByteBuffer类型的wrap(byte [])方法不适用于   参数(InputStream)”

尝试2:

    URL url = new URL(imagePath);
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    try (InputStream inputStream = url.openStream()) {
        int n = 0;    
        byte[] buffer = new byte[1024];    
        while (-1 != (n = inputStream.read(buffer))) {
            output.write(buffer, 0, n);
        }
    }
    byte[] img = output.toByteArray();    
    ByteBuffer imageBytes = ByteBuffer.wrap(img);    

我也尝试过此功能,但它显示此错误:

  

java.io.IOException:服务器返回URL的HTTP响应代码:403:   https://www.clearias.com/up/UPSC-Civil-Services-Mains-Exam-2018-Timetable-V1.png

尝试3: 另一个是

byte[] img = Base64.encodeBase64(IOUtils.toByteArray((new URL(imagePath)).openStream()), true);    

此行也给我错误

2 个答案:

答案 0 :(得分:3)

HTTP错误403表示服务器已完全理解您请求此图像并下载它的意图。但是,它估计您无权这样做,不是因为编程错误,而是因为您不应被允许这样做。

通常得出的结论是,不可能仅从其URL获取此图像,并且可能需要在请求旁边提供某种形式的身份验证,以向服务器证明应允许您获取该图像。

但是很明显,仅通过在浏览器中复制/粘贴URL,就可以确定服务器在“正常”条件下无条件发出图像。服务器仅在由Java程序发出请求时才拒绝该请求(我也没有测试其他技术)。剩下的问题是,服务器如何分辨该请求是由Java程序发出的?或者,更笼统地说,服务器如何决定您是否有权提出此请求?

从理论上讲,我们无法猜测每个人的意图,但是对于想要拒绝来自特定技术的请求的HTTP服务器,通常会基于请求的User-Agent HTTP标头执行此操作。因此,我决定修改Java默认发送的User-Agent,然后撒谎并假装请求是由Firefox完成的(非常幼稚的方式)

代码如下:

URL url = new URL(imagePath);
ByteArrayOutputStream output = new ByteArrayOutputStream();
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Firefox");

try (InputStream inputStream = conn.getInputStream()) {
  int n = 0;
  byte[] buffer = new byte[1024];
  while (-1 != (n = inputStream.read(buffer))) {
    output.write(buffer, 0, n);
  }
}
byte[] img = output.toByteArray();
ByteBuffer imageBytes = ByteBuffer.wrap(img);

有效。

答案 1 :(得分:1)

我想网址有问题。

使用Apache commons-io Apache commons-io

下面是示例代码:

import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

public class DownloadImage {
    public static void main(String[] args) {

        try {
            URL url = new URL("https://en.wikipedia.org/wiki/Car#/media/File:401_Gridlock.jpg");
            System.out.println(Arrays.toString(downloadFile(url)));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private static byte[] downloadFile(URL url) {
        try {
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.connect();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), baos);

            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

输出: [..., 47, 98, 111, 100, 121, 62, 10, 60, 47, 104, 116, 109, 108, 62, 10]