【问题标题】:GET request works fine in Postman - 405 Not Allowed from Java codeGET 请求在 Postman 中运行良好 - Java 代码中不允许出现 405
【发布时间】:2020-07-08 11:26:20
【问题描述】:

我正在尝试向以下网址发出 GET HTTP 请求:https://xml.betfred.com/horse-racing-us.xml

它被我使用 Apache 或 OKHTTP 的 Java 代码阻止,但在 Postman 中每次都可以正常工作,而无需任何额外的标头等。

我从我的代码中得到的响应是:

Response{protocol=http/1.1, code=405, message=Not Allowed, url=https://xml.betfred.com/horse-racing-us.xml}

为什么它在 Postman 中有效,但在其他地方无效?

    String URL = "https://xml.betfred.com/horse-racing-us.xml";

    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("Cache-Control", "no-cache");
    headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36");
    headers.put("Connection", "keep-alive");
    headers.put("accept", "application/json");

    JSONObject object = null;
    try {
        object = JSONHelper.readJsonFromUrl(URL, headers);
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();


public static JSONObject readJsonFromUrl(String urlString, HashMap<String, String> headers) throws IOException, JSONException {
    HttpURLConnection urlConnection = null;

    URL url = new URL(urlString);

    urlConnection = (HttpURLConnection) url.openConnection();

    Iterator<Entry<String, String>> it = headers.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> pair = (Map.Entry<String, String>)it.next();
        urlConnection.setRequestProperty(pair.getKey(), pair.getValue());
    }

    urlConnection.setReadTimeout(10000 /* milliseconds */ );
    urlConnection.setConnectTimeout(15000 /* milliseconds */ );
    urlConnection.setDoOutput(true);

    urlConnection.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    StringBuilder sb = new StringBuilder();

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }
    br.close();

    String jsonString = sb.toString();

    urlConnection.disconnect();

    return new JSONObject(jsonString);
}

【问题讨论】:

  • 您可以将代码添加到您的问题中吗?
  • 已添加代码。谢谢
  • 我刚刚尝试使用 curl,也得到了 405,但它在浏览器中工作正常。他们一定是在检查与用户代理有关的事情
  • 我认为您的 User-Agent 标头未正确应用。
  • 我做了一些测试,你的代码对我来说很好。在这个阶段我唯一能想到的就是你在实际代码中的User-Agent 有一个错字。仅供参考,如果使用任何最新版本的 Java,您可以将标头代码缩短为 headers.forEach(urlConnection::setRequestProperty)

标签: api http postman okhttp


【解决方案1】:

此消息表明,HTTP 版本 1.1 的 GET 方法是不允许的。

看起来是版本不匹配。当您在浏览器中打开该网站时,该网站支持 HTTP 版本 2。你可以尝试用 OkHttp 替换 Java 的内置 HttpUrlConnection,因为 OkHttp 支持 HTTP 版本 2。你必须升级你的 JVM。在我的 JVM(构建 1.8.0_241-b07)中,当我运行此代码-sn-p 时,选择了 HTTP 版本 2。

【讨论】:

    猜你喜欢
    • 2021-03-10
    • 2020-05-21
    • 2016-10-10
    • 1970-01-01
    • 2019-05-15
    • 2020-03-19
    • 2020-04-29
    • 2017-01-27
    • 2012-11-29
    相关资源
    最近更新 更多