繁体   English   中英

Java禁止代码错误,但浏览器错误(2)

[英]Java forbidden error with code but not with browser (2)

以下代码下载具有指定网址的图片。 但是某些网址出现403错误。

根据此链接 ,我尝试使用setRequestProperty(),但仍然无法解决我的问题。 我无法弄清楚自己犯的错误,还是应该在代码中添加更多内容?

import java.io.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.HttpURLConnection;

class Crawler{

    public static void main(String args[]){

        String address = "http://szcdn1.raagalahari.com/dec2016/hd/anupama-parameswaran-premam-hd-photos/anupama-parameswaran-premam-hd-photos294.jpg";
        Connection connection1 = new Connection();
        connection1.connector(address);

    }   
}

class Connection{
    void connector(String s){
        try{    
            URL url = new URL(s);
            URLConnection uc = url.openConnection();
            HttpURLConnection http_connection = (HttpURLConnection) uc;
            http_connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36");

            http_connection.connect();
            ImageDownload downloader = new ImageDownload();
            downloader.download(url);   

        }catch(Exception e) {
            System.out.println(e);
        }       
    }
}

class ImageDownload{

    void download(URL u){
        try
        { 

            InputStream in = new BufferedInputStream(u.openStream());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int n = 0;

            while (-1!=(n=in.read(buf))){
                out.write(buf, 0, n);
            }

            out.close();
            in.close();

            byte[] response = out.toByteArray();


            FileOutputStream fos = new FileOutputStream("C://3.jpg");
            fos.write(response);
            fos.close();
        } catch(IOException e){
             System.out.println(e);
        }
    }
}

如果问题重复,对不起。 请帮忙..

403错误几乎总是由您尝试访问您无权访问的内容引起的。

尝试使用这个

http_connection.setRequestProperty("http-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

您的download()方法使用Java的默认连接参数,使用URL.openStream()从头开始建立连接。 您准备的http_connection无效,因为您的代码未在进行工作的download()方法中使用它。

因此,应该将http_connection传递给download()方法,而不是URL,并使用其getInputStream()方法代替URL.openStream()。 然后,您将看到请求属性的效果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM