无法使用HttpURLConnection下载图像

Dee*_*pak 1 php java

我正在尝试下载文件http://images.anandtech.com/doci/5434/X79%20Extreme9Box_575px.jpg

但无法使用HttpUrlConnection,ImageIO.read甚至在php中使用file_get_contents下载它.

我无法弄清楚为什么会发生这种情况,但如果我在浏览器中检查此链接,那么在Firefox和歌剧中的标题响应都是200

请帮我

现在我注意到我收到了400个代码.

线程"main"中的异常java.io.IOException:服务器返回HTTP响应代码:400为URL:http://images.anandtech.com/doci/5478/Screen Shot 2012-01-30 at 4.21.52 PM_575px.png at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)

anu*_*ava 7

这是一个Java方法,您可以使用URLConnection下载和保存资源:

public void saveStream( String mURL, String ofile ) throws Exception {
    InputStream in = null;
    FileOutputStream out = null;
    try {
        URL url = new URL(mURL);
        URLConnection urlConn = url.openConnection();
        in = urlConn.getInputStream();
        out = new FileOutputStream(ofile);
        int c;
        byte[] b = new byte[1024];
        while ((c = in.read(b)) != -1)
            out.write(b, 0, c);
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

saveStream("http://images.anandtech.com/doci/5434/X79%20Extreme9Box_575px.jpg",
           "/home/john/saved.gif");
Run Code Online (Sandbox Code Playgroud)


Ran*_*Rag 5

它对我来说很好。

String path = "C:\\image.jpg";
URL url = new URL("http://images.anandtech.com/doci/5434/X79%20Extreme9Box_575px.jpg");
BufferedImage image = ImageIO.read(url);
ImageIO.write(image, "jpg", new File(path));
Run Code Online (Sandbox Code Playgroud)

您也可以尝试User-Agent在代码中添加字符串。

URLConnection myconn = url.openConnection();

myconn.setRequestProperty("User-Agent","User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
Run Code Online (Sandbox Code Playgroud)