How to resolve the error - statuscode 302?

1.7K    Asked by BuffyHeaton in Salesforce , Asked on Apr 28, 2023

I tried making an http callout and the response received is a redirection error as per below: System.HttpResponse[Status=Moved Temporarily, StatusCode=302] . Is there any work around to handle the redirection for HttpRequest objects in salesforce.

I also tried to make the callout in loop until we get the response but no success (as suggested HTTP Callout Error)

Answered by elonjigar

Some HTTP client code handles this automatically but in Apex you have to do the work yourself.

Documentation about HTTP 302 explains:
The HTTP response status code 302 Found is a common way of performing URL redirection.
An HTTP response with this status code will additionally provide a URL in the location header field. The user agent (e.g. a web browser) is invited by a response with this code to make a second, otherwise identical, request to the new URL specified in the location field.
So when you get this status code you need to make a second request using the value you find in the location header of the first response e.g.:
HttpResponse res = new Http().send(req); while (res.getStatusCode() == 302) { req.setEndpoint(res.getHeader('Location')); res = new Http().send(req); }


Your Answer

Answer (1)

To resolve an HTTP 302 status code error, you need to understand and correctly handle the temporary redirect that the server is signaling. Here’s a step-by-step approach to resolving and managing a 302 status code:


1. Understand the 302 Status Code

The 302 status code indicates a temporary redirect. The server is telling the client that the requested resource is temporarily located at a different URL, specified in the Location header of the response.

2. Follow the Redirect

Most modern web browsers and HTTP clients automatically follow the redirect specified by the 302 status code. If you're writing code to handle HTTP requests, ensure your HTTP client is configured to follow redirects.

Example in Python using requests library

import requests
response = requests.get('http://example.com')
print(response.url) # Prints the final URL after following the redirect

print(response.status_code) # Should print 200 if the redirect was followed successfully

By default, requests follow redirects. If you want to handle it manually:

import requests




response = requests.get('http://example.com', allow_redirects=False)
if response.status_code == 302:
    redirect_url = response.headers['Location']
    response = requests.get(redirect_url)
print(response.url)
print(response.status_code)

3. Check the Location Header

When you receive a 302 status code, inspect the Location header in the response. This header contains the URL where the resource has been temporarily moved.

Example using cURL

curl -I http://example.com
5 Months

Interviews

Parent Categories