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
mpdillonAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
What kind of  authentication do you need? What does the spec says?
0
mpdillonAuthor Commented:
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.
0
mpdillonAuthor Commented:
It is basic authentication.
0
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

ste5anSenior DeveloperCommented:
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

0
mpdillonAuthor Commented:
On site elsewhere now. Will try later today and let you know. Thanks. It looks correct to me.
0
mpdillonAuthor Commented:
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
0
ste5anSenior DeveloperCommented:
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).
0
mpdillonAuthor Commented:
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.
0
ste5anSenior DeveloperCommented:
Image? This may be already the problem. An image is often uncompressed in memory.. Especially when you do some Bitmap fiddling.
0
mpdillonAuthor Commented:
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
0
ste5anSenior DeveloperCommented:
The Console.ReadLine() waits for any key, so that the program does not terminate instantly. So that you can see any output when running it in VS.

The memory error must be in the rest of your code or machine has some weird memory fragmentation issue.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mpdillonAuthor Commented:
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?
0
mpdillonAuthor Commented:
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
0
mpdillonAuthor Commented:
Thanks for staying with me. I know it took a long time to resolve.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.