Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JAVA中的查询参数从链接下载图像_Java_Image_Urlconnection - Fatal编程技术网

使用JAVA中的查询参数从链接下载图像

使用JAVA中的查询参数从链接下载图像,java,image,urlconnection,Java,Image,Urlconnection,在java代码的帮助下,我正在从link下载图像 public static BufferedImage ImageDownloader(String urlString){ BufferedImage image = null; try { URL url = new URL(urlString.replace(" ","%20")); URLConnection connection = url.openConnection();

在java代码的帮助下,我正在从link下载图像

public static BufferedImage ImageDownloader(String urlString){
    BufferedImage image = null;
    try {
        URL url = new URL(urlString.replace(" ","%20"));
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        image = ImageIO.read(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;
}
上面的代码可以完美地下载图像,但它不能用这样的链接下载图像

我知道我可以删除该查询参数并更新url,但还有比这更好的解决方案吗?

使用
transferFrom()


只是不要设置用户代理:

public static BufferedImage ImageDownloader(String urlString){
    BufferedImage image = null;
    try {
        String cleanUrl = urlString.replace(" ","%20");
        URL url = new URL(cleanUrl);
        URLConnection connection = url.openConnection();
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        image = ImageIO.read(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;
}
或者:

public static BufferedImage ImageDownloader(String urlString){
    BufferedImage image = null;
    try {
        String cleanUrl = urlString.replace(" ","%20");
        URL url = new URL(cleanUrl);
        image = ImageIO.read(url.openStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;
}
或者:

public static BufferedImage ImageDownloader(String urlString){
    BufferedImage image = null;
    try {
        URL url = new URL(urlString.replace(" ","%20"));
        image = ImageIO.read(url);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;
}
public static BufferedImage ImageDownloader(String urlString){
    BufferedImage image = null;
    try {
        URL url = new URL(urlString.replace(" ","%20"));
        image = ImageIO.read(url);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;
}