Java 无法使用HttpURLConnection下载映像
我正在尝试下载文件 但无法使用HttpUrlConnection、ImageIO.read下载它,甚至无法在php中使用file_get_内容下载它 我不知道为什么会发生这种情况,但如果我在浏览器中检查这个链接,那么firefox和opera中的标题响应都是200 请帮帮我 现在我注意到我收到了400码 线程“main”java.io.IOException中的异常:服务器返回了URL:Shot 2012-01-30在下午4.21.52_575px.png的HTTP响应代码:400 位于sun.reflect.NativeConstructorAccessorImpl.newInstance0(本机方法)Java 无法使用HttpURLConnection下载映像,java,php,Java,Php,我正在尝试下载文件 但无法使用HttpUrlConnection、ImageIO.read下载它,甚至无法在php中使用file_get_内容下载它 我不知道为什么会发生这种情况,但如果我在浏览器中检查这个链接,那么firefox和opera中的标题响应都是200 请帮帮我 现在我注意到我收到了400码 线程“main”java.io.IOException中的异常:服务器返回了URL:Shot 2012-01-30在下午4.21.52_575px.png的HTTP响应代码:400 位于sun.
在sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)服务器可能只允许特定的用户代理访问映像。尝试通过
connection.setRequestProperty(“用户代理”、“Mozilla/5.0”)代码>可能服务器只允许特定的用户代理访问映像。尝试通过connection.setRequestProperty(“用户代理”、“Mozilla/5.0”)代码>以下是一个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();
}
}
这样称呼它:
saveStream("http://images.anandtech.com/doci/5434/X79%20Extreme9Box_575px.jpg",
"/home/john/saved.gif");
以下是一个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();
}
}
这样称呼它:
saveStream("http://images.anandtech.com/doci/5434/X79%20Extreme9Box_575px.jpg",
"/home/john/saved.gif");
这对我来说很好
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));
您还可以尝试在代码中添加用户代理
字符串
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");
这对我来说很好
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));
您还可以尝试在代码中添加用户代理
字符串
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");
编辑得不错+1删除了一些噪音。编辑得不错+1删除了一些噪音。URL中的
未正确编码为%20
。URL中的
未正确编码为%20
。