Power Automate does not handle 302 redirects out of the box like other web clients do.
A 302 redirect is when an API replies with a url that it expects you to then follow. A 301 is a permanent redirect (e.g change or url when rebranded) and a 302 is temporary (often for security).
The only way I have seen to handle it is to catch the exception and then use the redirect url in a new http call (the url is normally returned in the Location header).
But this is not great if you want to scale out the connection (and let's be honest it's a little janky). To do it properly we need a custom connector, but guess what, they don't handle them either. Luckily there is a way, and thats so use some custom code.
The code will automatically follow the redirect url and pass on the response.
public class Script : ScriptBase
{
public override async Task<HttpResponseMessage> ExecuteAsync()
{
// Use the context to forward/send an HTTP request
HttpResponseMessage response = await this.Context.SendAsync(this.Context.Request, this.CancellationToken).ConfigureAwait(false);
// Check if the response is a 302 redirect
if (response.StatusCode == HttpStatusCode.Found)
{
// If has Loocation Header extract the redirect URL from the Location header
if (response.Headers.Location != null)
{
var redirectUrl = response.Headers.Location.ToString();
// Create a new request with the redirect URL
var redirectRequest = new HttpRequestMessage(HttpMethod.Get, redirectUrl);
// Forward the new request to the redirect URL
response = await this.Context.SendAsync(redirectRequest, this.CancellationToken).ConfigureAwait(true);
}
else
{
// If the Location header is not present, return an error response
response = new HttpResponseMessage(HttpStatusCode.BadRequest);
response.Content = CreateJsonContent("Location header missing in the redirect response.");
}
}
else if (response.IsSuccessStatusCode)
{
// If the response is successful, perform any necessary transformations
var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
// Example case: response string is some JSON object
var result = JObject.Parse(responseString);
// Wrap the original JSON object into a new JSON object with just one key ('wrapped')
var newResult = new JObject
{
["wrapped"] = result,
};
response.Content = CreateJsonContent(newResult.ToString());
}
return response;
}
}
And that's it, it should work on any api and means your custom connector will act like one api call and not need exception handling.
>----------------------------------------------------------------------------------------------------------------------------------------------
This is a series of short blogs designed to help find solutions for random problems before you ask, keep your eyes out for more
l also do long form and broader Power Platform blogs here https://dev.to/wyattdave
*This post is locked for comments