访问URL时出错403但在浏览器中工作正常

Pra*_*eep 8 java

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();
Run Code Online (Sandbox Code Playgroud)

我使用BufferedReader来打印我得到的内容403错误

相同的URL在浏览器中正常工作.任何人都可以建议.

Tim*_*per 8

它在浏览器中工作但在java代码中不起作用的原因是浏览器添加了一些您在Java代码中缺少的HTTP头,并且服务器需要这些头.我一直处于相同的情况 - 这个网址在Chrome和Chrome插件"简单REST客户端"中都有效,但却无法在Java中运行.在getInputStream()之前添加此行解决了问题:

                connection.addRequestProperty("User-Agent", "Mozilla/4.0");
Run Code Online (Sandbox Code Playgroud)

..尽管我从未使用过Mozilla.您的情况可能需要不同的标题.它可能与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);
        }
Run Code Online (Sandbox Code Playgroud)


Buh*_*ndi 3

HTTP 403禁止状态代码。您必须阅读 才能HttpURLConnection.getErrorStream()查看服务器的响应(它可以告诉您为什么收到 HTTP 403)(如果有)。