Java HTTP GET请求给出403 Forbidden,但在浏览器中工作



我有一些代码,这意味着通过HTTP向服务器发送GET请求,并在那里获取数据。我还没有对处理响应的部分进行编码,因为我首先想测试GET请求是否有效。它没有:

private static String fetch() throws UnsupportedEncodingException, MalformedURLException, IOException {
        // Set the parameters
        String url = "http://www.futhead.com";
        String charset = "UTF-8";
        //Fire the request
        try {
        URLConnection connection = new URL(url).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        // ^^^ I tried this, and it doesn't help!
        InputStream response = connection.getInputStream();
        HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
        httpConnection.setRequestMethod("GET");
        System.out.println("Status: " + httpConnection.getResponseCode());
        } catch (UnknownHostException e) {
            // stuff
        }
        return null;
        // ^^^ I haven't coded the fetching itself yet
    }

考虑到该代码,fetch()打印Status: 403。为什么会发生这种情况?我的猜测是,这个特定的服务器不让非浏览器客户端访问它(因为代码工作与http://www.google.com),但有一个解决方案?

已经有一些答案了,但其中一些要么与我无关(他们谈论的是HTTPS的问题),要么是难以理解的。我试过那些我能理解的,但无济于事。

您可能已启用浏览器完整性检查https://support.cloudflare.com/hc/en-us/articles/200170086-What-does-the-Browser-Integrity-Check-do-

我禁用了浏览器完整性检查,它现在工作正常。如果可能的话,另一个解决方案是设置User-Agent。

我在Scala中遇到了这个问题,它最终使用java.net.URL

相关内容

最新更新