system.net.webclient post error 400

alessandro belli 131 Reputation points
2024-03-06T13:42:33.91+00:00

I have this HTTP post that with curl under w10 work fine

curl https://auth.sinch.com/oauth2/token -d grant_type=client_credentials -u username:password

This require a basic authentication and return a token

I need to implement this under vb.net (frameworks 4.5.2)

I've tyred with system.net.webclient (I've already used for other similar) but I always get error 400.

This is the code:

Dim myCreds As NetworkCredential = New NetworkCredential("Myusername", "Mypassword")

    Dim url As String = "https://auth.sinch.com/oauth2/token"  

    Using client As New WebClient 'POST

        client.Credentials = myCreds

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

        client.Headers.Add("Content-Type", "application/x-www-form-urlencoded")

           Dim result As String = client.UploadString(url, "POST", "grant_type=client_credentials")

    End Using
```Any Idea where is the error? 

Thank you

Alessandro

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,650 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,668 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 29,261 Reputation points Microsoft Vendor
    2024-03-07T06:35:25.07+00:00

    Hi @alessandro belli ,

    Try sending the credentials in the request body.

            Dim url As String = "https://auth.sinch.com/oauth2/token"
            Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes("Myusername:Mypassword"))
            Dim postData As String = "grant_type=client_credentials"
    
            Using client As New WebClient()
                client.Headers(HttpRequestHeader.Authorization) = "Basic " & credentials
                client.Headers(HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    
                Dim responseBytes As Byte() = client.UploadData(url, "POST", Encoding.ASCII.GetBytes(postData))
                Dim responseBody As String = Encoding.ASCII.GetString(responseBytes)
    
                Console.WriteLine(responseBody)
            End Using
    
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful