【问题标题】:Java forbidden error with code but not with browser (2)Java禁止错误代码但浏览器没有错误(2)
【发布时间】:2017-06-24 17:24:41
【问题描述】:

以下代码下载具有指定 url 的图像。但我收到一些网址的 403 错误。

根据link,我尝试使用 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);
        }
    }
}

如果问题重复,请提前道歉。请帮忙。。

【问题讨论】:

    标签: java httpurlconnection http-status-code-403


    【解决方案1】:

    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");
    

    【讨论】:

      【解决方案2】:

      您的 download() 方法使用 URL.openStream() 使用 Java 的默认连接参数从头打开其连接。您准备的 http_connection 无效,因为您的代码没有在执行工作的 download() 方法中使用它。

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

      【讨论】:

      • 所以我做了这些改变:1.'downloader.download(http_connection)' 2.'void download(HttpURLConnection u)' 3.'InputStream in = u.getInputStream();'但这给了我同样的错误:服务器返回 HTTP 响应代码:403
      猜你喜欢
      • 2010-12-13
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      相关资源
      最近更新 更多