We help IT Professionals succeed at work.

How to force/Manually add authenticaion to POST WebRequest

220 Views
Last Modified: 2015-10-18
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
Comment
Watch Question

ste5anSenior Developer
CERTIFIED EXPERT

Commented:
What kind of  authentication do you need? What does the spec says?

Author

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.

Author

Commented:
It is basic authentication.
ste5anSenior Developer
CERTIFIED EXPERT

Commented:
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

Author

Commented:
On site elsewhere now. Will try later today and let you know. Thanks. It looks correct to me.

Author

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
ste5anSenior Developer
CERTIFIED EXPERT

Commented:
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).

Author

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.
ste5anSenior Developer
CERTIFIED EXPERT

Commented:
Image? This may be already the problem. An image is often uncompressed in memory.. Especially when you do some Bitmap fiddling.

Author

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
Senior Developer
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

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?

Author

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

Author

Commented:
Thanks for staying with me. I know it took a long time to resolve.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.