Search code examples
javahttpurlconnection

Not able to find location field for this particular site "http://www.macys.com/"


I have the following site : "http://www.macys.com/" for which there is redirection.

This is code snippet:

String location = "http://www.macys.com/";
do {
    HttpURLConnection conn = null;
    try {
        url = location;
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        /**
         * Setting the Browser properties
         */
        conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76 Safari/537.36");
        conn.setConnectTimeout(2000);
        conn.setInstanceFollowRedirects(false);
        conn.setReadTimeout(10000);
        conn.connect();
    } catch (Exception e) {
        logger.error("Exception : {}", e.getMessage());
    }

    responseCode = connection.getResponseCode();

    if ((responseCode > 300 && responseCode < 310)) {
        location = connection.getHeaderField("Location");
        if (location == null)
            break;
    }
} while (responseCode > 300 && responseCode < 310);

After first iteration, response code is 302, but no location field is found.

What am I doing wrong here?


Solution

  • If you look at the response body, you can see that the site is denying your request.

    Access Denied: You don't have permission to access the requested URL on this server.

    The site won't send you a Location header despite showing response code of 302 when they deny you access.