301 redirect - reading the response header

I have a 3rd party service where I send a request and get 301 redirect response back with a link to a pdf file.

What I want to do is send the request to the 3rd party service, then read the response header (dont want to be redirected), read the location header response and work with that.

Here is an example of the response

HTTP/1.1 301 Moved Permanently
< Date: Tue, 10 May 2022 08:27:08 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 421
< Connection: keep-alive
< Access-Control-Allow-Origin: *
< Location: https://s3.amazonaws.com/service/path/accounts/333/documents/20211119.pdf
< Vary: Origin

I want to read that Location response. I canโ€™t seem to figure out how to do this. Any suggestions?

what code are you using to get that response?

you could try without following the redirects, depending on what you use

Figured it out. What was stopping me is that my url was wrong so I got error before I got response.

Just in case somebody is wondering

let httpResponse = await Moralis.Cloud.httpRequest({
            method: 'GET',
            url: url,
        }).then(function(httpResponse :any) {
            if (httpResponse.headers && httpResponse.headers.location) {
                return httpResponse.headers.location;
        }).catch((reason : any) => {
            //handle error

So the header I was looking for is available through

@cryptokid thanks for the reply, you are always super quick :slight_smile: Sorry for not defining where I was doing this, that would have made things clearer. Iโ€™ll remember that next time

1 Like

Here is a Python example using the โ€œrequestsโ€ library.

import requests

url = 'https://example.com/your-request-url'
response = requests.get(url, allow_redirects=False)

if response.status_code == 301:
    location = response.headers.get('Location')
    if location:
        print("Redirect location:", location)
        print("No redirect location found in the response headers.")
    print("The response is not a 301 redirect.")

Make sure to replace 'https://example.com/your-request-url' with the actual URL you are sending the request to. Additionally, ensure that you have the requests library installed in your Python environment.

You can verify your URL on any online toot such as this RedirectChecker.com to get its detail Redirection chain and its status code.