【发布时间】: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)