GET请求在Postman中正常工作--Java代码中405不允许。

问题描述 投票:1回答:1

我试图对以下网址进行GET HTTP请求。https:/xml.betfred.comhorse-racing-us.xml。

使用Apache或OKHTTP时,我的Java代码会被阻止,但在Postman中每次都能正常工作,不需要任何额外的头信息等。

我从我的代码中得到的回答是:"为什么它在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);
}
api http postman okhttp
1个回答
0
投票

这条信息表明,HTTP版本1.1的GET方法是不允许的。

它看起来像一个版本不匹配。该网站支持HTTP版本2,当你在浏览器中打开它。你可以尝试替换Java的内置的 HttpUrlConnection 因为OkHttp支持HTTP版本2。你必须升级你的JVM。在我的JVM(build 1.8.0_241-b07)中,当我运行这段代码时,HTTP版本2被选择了。

© www.soinside.com 2019 - 2024. All rights reserved.