post error 400

alessandro belli 131 Reputation points

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

curl -d grant_type=client_credentials -u username:password

This require a basic authentication and return a token

I need to implement this under (frameworks 4.5.2)

I've tyred with (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 = ""  

    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


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

Accepted answer
  1. Jiachen Li-MSFT 26,426 Reputation points Microsoft Vendor

    Hi @alessandro belli ,

    Try sending the credentials in the request body.

            Dim url As String = ""
            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)
            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