当前位置: 代码迷 >> J2EE >> HttpURLConnection 读取网络图片的有关问题 急求
  详细解决方案

HttpURLConnection 读取网络图片的有关问题 急求

热度:481   发布时间:2016-04-17 23:42:35.0
HttpURLConnection 读取网络图片的问题 急求
在用HttpURLConnection 读取网络图片时候 出现 404 错误 求大神指点 ?

http://www.offerwow.cn/image/offerwow_staging/logo/1406880082963.jpg  
这个地址用浏览器打开 是可以正常访问的 但是用 HttpURLConnection  去读取 会出现 404 错误



                       URL url = new URL("http://www.offerwow.cn/image/offerwow_staging/logo/1406880082963.jpg");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setReadTimeout(30000);
con.setInstanceFollowRedirects(true);
con.addRequestProperty("Cache-Control", "no-cache");
con.connect();
// 在指定目录创建一个空文件并获取文件对象
File file = new File("H:\\a.jpg");
if (file.exists()) { file.delete(); }else{ file.createNewFile();}
// 获取一个写入文件流对象
String location = con.getHeaderField("Location");
System.out.println(location);    //这里打印 null 
System.out.println(con.getURL().toString());    //这里打印http://www.offerwow.cn/image/offerwow_staging/logo/1406880082963.jpg
InputStream in = con.getInputStream();   //这句出异常






------解决思路----------------------
你看看直接访问域名有没有变,应该以能看到图片的地址栏地址为准。
------解决思路----------------------

URL url = new URL("http://www.offerwow.cn/image/offerwow_staging/logo/1406880082963.jpg");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1");
        con.setRequestProperty("accept-language", "zh-CN");
        con.setInstanceFollowRedirects(true);
        con.addRequestProperty("Cache-Control", "no-cache");
        con.connect();
        System.out.println(con.getURL().toString());    //这里打印http://www.offerwow.cn/image/offerwow_staging/logo/1406880082963.jpg
        int code=con.getResponseCode();
        System.out.println(con.getURL().toString());    //这里打印http://www.offerwow.cn/image/offerwow_staging/logo/1406880082963.jpg

自己看下打印的url还不明白吗?302必须设置User-agent和accept-language,跳转是浏览器帮你的。
  相关解决方案