Link to home
Start Free TrialLog in
Avatar of mpdillon
mpdillon

asked on

How to force/Manually add authenticaion to POST WebRequest

I need to provide authentication for a POST request. I have never done this before so I have been searching for methods to accomplish this.
I have found this method but it did not work. The message I received was 401 Unauthorized.
Dim myCred As New NetworkCredential("USERNAME", "PASSWORD")
        Dim credsCache As New CredentialCache()
        credsCache.Add(New Uri(Uri), "Basic", myCred)
        Dim request As WebRequest = WebRequest.Create(Uri)
        request.Credentials = credsCache

Open in new window


I found other posts indicating that sometimes the authentication has to be forced. I have been trying to get this code to work but I do not know how to declare the AUTHORIZATION
Dim request As WebRequest
Dim credidentials As String = "userName" + ":" + "Password"
Authorization = Convert.ToBase64String(Encoding.[Default].GetBytes(credidentials))  'How do I declare Authorization?
request.Headers("Authorization") = "Basic " + Authorization

Open in new window


How do I declare authorization or how do I "force" authorization?

Thanks,
pat
Avatar of ste5an
ste5an
Flag of Germany image

What kind of  authentication do you need? What does the spec says?
Avatar of mpdillon
mpdillon

ASKER

I was not given a type of authorization. But that is a really good question. I have never done this before and I did not know there were different types. I just checked and it is not listed in the spec.

I have requested that the authorization type be identified. I should hear back this morning.
It is basic authentication.
Seems you're pretty close..

This should work:

Imports System.Net
Imports System.Text

Module Module1

    Sub Main()

        Dim username As String = "username"
        Dim password As String = "passwort"
        Dim url As String = "http://your.url"
        Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password))

        Dim webClient As WebClient = New WebClient()

        webClient.Headers(HttpRequestHeader.Authorization) = "Basic " + credentials
        webClient.UploadString(url, "your string")

        Console.WriteLine("Done.")
        Console.ReadLine()

    End Sub

End Module

Open in new window

On site elsewhere now. Will try later today and let you know. Thanks. It looks correct to me.
Ok. Thank you.  I ran into an error. Please see the attached image.

Also when I read the code earlier today, I didn't notice that there does not seem to be a RESPONSE component. In my scenario, my code is to POST string to a web sever and listen for the RESPONSE. At the moment I do not know how to tell if the POST was successful. How would I add that to the code?
Thanks,
pat
WebClient-error.png
This means, that you're running out of memory on your machine. See Troubleshooting the error "Not enough storage is available to complete this operation".

So I would reboot the machine and see whether that error is reproducible. If so, what does x in you sample contain? I would start testing the upload procedure with a simple and short string. Cause I think the error may depend on the way you're handling the XML (those reader lines in your image).
The length of x is 6784 characters. Task manager indicates that 2.5 GB on 5.8 GB of memory are being used. I will reboot and try again.

Unfortunately, I do not have the option of testing with a short string. The Company receiving the data is a large multinational and they are a bit inflexible.

The string I am sending is a XML notification of shipment. The bulk of its length is due the signature image which I converted to Base 64.
Image? This may be already the problem. An image is often uncompressed in memory.. Especially when you do some Bitmap fiddling.
I apologize for the delay. There was a windows update that got hung on this workstation.

After the reboot, the same error occurred.

The code to convert the image to base 64 seems straight forward to me. I have attached the string, x, that is being posted. To that string I have added a few carriage returns to isolate the signature text. I have also tried to find all references that might identify the companies involved. I have changed every reference I could identify.

In addition to the error there is something I do not understand. What is Console.ReadLine doing? Is it reading a response somehow? If so I need to read that response into a string variable and compare it to the possible response from the server. I haven't been given those responses yet but I am sure I will receive them at some point.

Thank you very much for our continued interest. I would not be making any progress without your assistance.
InfoTobePosted.txt
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK. Thanks for the explanation. I did the exact same thing when I started this program. I first built it as a console app. I tested the console app there first to ensure I had the ServiceContract, DataContract and DataMembers correct. I had never done this before. I built a Client console app for testing. Testing yielded the results I expected. I did not realize I could use a console command in a non console app.
Anyway I tried several different methods to Build a response for the WebClient in the code you shared but was not successful. I would like the response to read directly into a string variable. How would I do that?
Thank you for all your assistance. I have finally arrived at a solution. Below is my final code for POST with BASIC Authentication

Private Sub PostXMLfile(ByVal x As String, ByRef WebString As String)
        Dim username As String = "username"
        Dim password As String = "password"
        Dim request As HttpWebRequest
        Dim response As HttpWebResponse = Nothing
        Dim reader As StreamReader
        Dim xmlDocAsStr As String = x
        Dim byteArray(xmlDocAsStr.Length - 1) As Byte
        Dim objUTF8Encoding As New UTF8Encoding
        Dim Uri As String = "https://test.com/invoke/B2BShipmentDeliveryStatus.externalCarriers.services:receiveConfirmation"
        Dim postStream As Stream = Nothing
        'Some code from: https://developer.yahoo.com/dotnet/howto-rest_vb.html
        '
        Try
            ' Create the web request 
            request = DirectCast(WebRequest.Create(Uri), HttpWebRequest)
            byteArray = objUTF8Encoding.GetBytes(xmlDocAsStr)
            request.Method = "POST"
            request.ContentLength = byteArray.Length
            request.ContentType = "text/xml"
            ' Add authentication to request  
            request.Credentials = New NetworkCredential(username, password)
            '
            Try
                postStream = request.GetRequestStream()
                postStream.Write(byteArray, 0, byteArray.Length)
            Finally
                If Not postStream Is Nothing Then postStream.Close()
            End Try
            '' Get response  
            response = DirectCast(request.GetResponse(), HttpWebResponse)
            reader = New System.IO.StreamReader(response.GetResponseStream(), Encoding.ASCII)
            WebString = reader.ReadToEnd()
        Finally
            If Not response Is Nothing Then response.Close()
        End Try

    End Sub

Open in new window

Thanks again.
pat
Thanks for staying with me. I know it took a long time to resolve.