我正在尝试对以下URL进行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);
}
答案 0 :(得分:0)
此消息表示不允许使用HTTP 1.1版的GET方法。
似乎版本不匹配。在浏览器中打开该网站时,它支持HTTP版本2。您可以尝试用OkHttp替换Java的内置HttpUrlConnection
,因为OkHttp支持HTTP版本2。您必须升级JVM。在我运行此代码段的JVM(内部版本1.8.0_241-b07)中,选择了HTTP版本2。