这个地址copy到ie地址栏可以正常地显示图片,当我要用下面的代码下载的时候出错:Exception in thread "main" java.net.SocketException: Unexpected end of file from server
我用其他方式访问的时候有时候提示文件没有正常结束的错误
有知道怎么通过代码下载上面的jpg文件或者我下面额代码哪里写错了吗?3x
FileUtils和IOUtils来自Apache Common io包
File file = new File("D:\a.jpg");
FileUtils.writeByteArrayToFile(file,IOUtils.toByteArray(new URL(
"http://t2.baidu.com/it/u=%68%74%74%70%3a%2f%2f%6e%65%77%73%2e%6e%65%6e%2e%63%6f%6d%2e%63%6e%2f%69%6d%61%67%65%6c%69%73%74%2f%31%30%2f%32%38%2f%37%34%30%76%67%71%39%79%34%32%6a%74%2e%6a%70%67&fm=30").openStream()));
判断一下是不是被redirect了,如果是的话,则取出Location对应的值,再发一个URL请求。 下面是大致思路。
URLConnection connection = url.openConnection();
if (connection instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) connection;
http.setInstanceFollowRedirects(false);
int responseCode = http.getResponseCode();
System.out.println(responseCode);
boolean redirected = ((responseCode >= 300) && (responseCode <= 399));
if (redirected) {
String redirect = connection.getHeaderField("Location");
URL url2 = null;
if (redirect.startsWith("http")) {
url2 = new URL(redirect);
} else {
url2 = new URL(url, redirect);
}
。。。。。。。。。
}
这个URL根本没有指向一张图片.
而是指向一个Servlet之类的东西, 在Servlet中做了一些处理后, 再跳转到实际的图片路径上去.
这样做的好处是可以防盗链, 在Servlet中判断访问来源是否为本站.
也可以做多服务器负载均衡, 因为图片访问量这么大, 不可能全放在同一台服务器上的, 所以可以在Servlet中决定由哪个服务器来显示这张图片.
网站访问量比较大的一般都会有这样的设定.
楼主,你换个URL试试。你这个URL在浏览器都打不开。
楼主,问题解决了么?