403 when accessing the url but works fine in browsers

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();

and I use BufferedReader to print the content that I get with 403 error

The same URL works fine in the browser. Can anyone suggest.

+6
source share
6 answers

The reason it works in the browser, but not in the Java code, is because the browser adds some HTTP headers that you lack in your Java code, and the server needs these headers. I was in the same situation - and the URL worked in both Chrome and the Chrome plugin "Simple REST Client", but it didn’t work in Java. Adding this line before getInputStream () solved the problem:

                connection.addRequestProperty("User-Agent", "Mozilla/4.0");

.. 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);
        }
+7

HTTP 403 . HttpURLConnection.getErrorStream(), ( , HTTP 403), .

+2

. , , Google . , Google . - .

+2

URL- , URL- Java . URL- URLEncoder URL Encoder

0

, , URL- - Apache HttpComponents HttpClient: http://hc.apache.org/httpcomponents-client-ga/index.html

0

( ) .

original domain and target domain.

I found the difference in the request header:

with error 403,

         request header have one line:
                        Referer: http://original-domain/json2tree/ipfs/ipfsList.html

when I enter the URL 403 is denied, the request header does NOT have the above referrer lines: original-domain

I am finally figuring out how to fix this error !!!

on the web page of your source domain, you must add

              <meta name="referrer" content="no-referrer" />

it will remove or prevent sending Referer in the header, works for both links and Ajax requests

0
source

All Articles