Question

I am accessing a REST webservice from a VB app. I create a HttpWebResponse object and call GetRequestStream on it just fine, but when I call GetResponse I get a 401 exception.

Here is my code (modified for posting):

Dim webRequest = DirectCast(WebRequest.Create(endpoint), HttpWebRequest)
webRequest.Method = "POST"
webRequest.ContentLength = contentLength
webRequest.ContentType = "application/x-www-form-urlencoded"

request.Credentials = New NetworkCredential(Username, Password)

' Works fine
Using stream As Stream = webRequest.GetRequestStream()
    stream.Write(data, 0, data.Length)
End Using

' Barfs
Dim response As HttpWebResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)

I get a 401 exception as soon as I call "webRequest.GetResponse()". There is a "WWW-Authenticate" header in the response, with the appropriate realm. I have tried setting "webRequest.PreAuthenticate = True", as well as manually setting the header with "webRequest.Headers.Add(HttpRequestHeader.Authorization, _authheader)"

I can not seem to monitor these requests with Fiddler / Wireshark etc. because this is SSL traffic, I am sure there is a way to monitor it, I just have not found it yet.

Thanks in advance,

--Connor

Was it helpful?

Solution 3

Thank you everyone for your help! The problem was that I was being redirected! I think that all I need to do is change the address header to reflect the url that I will be redirected to at the successful completion of a post.

OTHER TIPS

Try adding manually adding the AUTHORIATION header, something like ...

string autorization = userName + ":" + password;
byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
autorization = Convert.ToBase64String(binaryAuthorization);
autorization = "Basic " + autorization;
webRequest.Add("AUTHORIZATION", autorization);

This has worked for me in the past where setting the Credentials property has failed.

It's certainly possible that this isn't your problem, but I've had authentication issues in the past that were fixed by setting

request.ProtocolVersion = HttpVersion.Version10
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top