Access raw response on HttpUtils.PostToUrl on response code 302

I am trying to use the HttpUtils to auth against a 3rd party API, using the HttpUtils.PostToUrl() functionality, but I am blocked because their API (application/x-www-form-urlencoded request) actually returns a 302 for a successful login (see https://dev.procountor.com/general-information/oauth/#step-1-authorization-code-grant).

Using either CURL or Fiddler, I can see that my login is successful according to their specification (CURL and Fiddler both show the return of a “Location” header, which I need to parse for the next step), but because the HttpUtils library throws a WebException on the 302, so I can never get access to the underlying header/response data.

Is there some way to suppress the HttpUtils from throwing the error, so I can get access to the underlying HttpWebResponse?

You can try disabling AutoRedirect’s, e.g:

var response = url.GetStringFromUrl(requestFilter:req => req.AllowAutoRedirect = false)

Was just about to write: I have actually already disabled the redirect, and thats what triggers the issue.

I’m running this code on my machine, it fires the auth call to Procountor, which successfully auths, but when I get the response back, it seems that its routed via the system I have in the redirecturl.

If I set the AllowAutoRedirect=true (default), with the redirect url set to the system it is supposed to target, i get a response successfully (contains some html from redirecturl system, but no Location header, presumably because its been rerouted already).

If I set AllowAutoRedirect=false, so the response should come back to me (running the code on my local machine), thats when I see the exception in HttpUtls when it recieves the 302 from Procountor…

So AllowAutoRedirect show success in Fiddler whether its true or false, but if true, the Location is missing from HttpUtils, and if false, the 302 kills my C# code.

That’s all the customization .NET’s HttpWebRequest (what HTTP Utils use) AFAIK.

You’ll either need to catch the Exception:

try {
    var response = url.GetStringFromUrl();
} 
catch (WebException ex)
{
    if (ex.IsAny300())
    {
       string body = ex.GetResponseBody();
       return body;
    }
    throw;
}

Otherwise you’ll have to use something more fine-grained like C# HttpClient.

1 Like
if (ex.IsAny300())
{
	string body = ex.GetResponseBody();
	location = ex.Response.Headers["Location"];
}

Works a treat… thanks. I hadn’t considered digging deeper into the WebException.

1 Like