【问题标题】:Java HTTP GET request gives 403 Forbidden, but works in browserJava HTTP GET 请求给出 403 Forbidden,但在浏览器中有效
【发布时间】:2014-05-03 14:07:34
【问题描述】:

我有一些代码,旨在通过 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 的问题)或难以理解。我已经尝试了那些我能理解的,但没有成功。

【问题讨论】:

  • 使用 Wireshark 并比较您的浏览器执行的请求和您的编码请求。由于特定的标题行使用丢失/不同,服务器可能会抛出 403。
  • 对。我是否查看浏览器发送的标头,并在我的 GET 中复制所有标头?
  • 我查看了网站设置的 cookie,它似乎使用了 CloudFlare,它设置了一个 __cfduid cookie。您可能需要handle this cookie
  • 我会试试的。但是,出于兴趣,为什么我需要处理 cookie 以避免 403?

标签: java http get


【解决方案1】:

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

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

我遇到了 Scala 的问题,它最终使用 java.net.URL

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 2016-07-11
    • 2011-01-19
    • 1970-01-01
    • 2018-06-30
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多