String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false";
URL google = new URL(url);
HttpURLConnection con = (HttpURLConnection) google.openConnection();
然后我使用 BufferedReader 打印我收到 403 错误的内容
相同的 URL 在浏览器中工作正常。任何人都可以建议。
最佳答案
它在浏览器中工作但在 java 代码中不起作用的原因是浏览器添加了一些 Java 代码中缺少的 HTTP header ,而服务器需要这些 header 。我遇到过同样的情况——该 URL 在 Chrome 和 Chrome 插件“Simple REST Client”中都有效,但在 Java 中无效。在 getInputStream() 之前添加这一行解决了问题:
connection.addRequestProperty("User-Agent", "Mozilla/4.0");
..尽管我从未使用过 Mozilla。您的情况可能需要不同的 header 。它可能与 cookie 有关...我在错误流中收到建议我启用 cookie 的文本。
请注意,您可能会通过查看错误文本获得更多信息。这是我的代码:
try {
HttpURLConnection connection = ((HttpURLConnection)url.openConnection());
connection.addRequestProperty("User-Agent", "Mozilla/4.0");
InputStream input;
if (connection.getResponseCode() == 200) // this must be called before 'getErrorStream()' works
input = connection.getInputStream();
else input = connection.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String msg;
while ((msg =reader.readLine()) != null)
System.out.println(msg);
} catch (IOException e) {
System.err.println(e);
}
关于java - 访问 URL 时出现 403 错误,但在浏览器中工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7485676/