Reputation: 445
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
Upvotes: 3
Views: 9083
Reputation: 445
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.
Upvotes: 1
Reputation: 51131
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
Upvotes: 0
Reputation: 3827
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.
Upvotes: 3