VB.NET - Salesforce POST Request returns 400 Bad Request Error

两盒软妹~` 提交于 2019-12-14 04:25:18

问题


NOTE: I've never written vb.net code before this. I've googled for a solution but did not find anything that worked.

I'm trying to get access token from Salesforce. Below code worked just yesterday. And I have no idea why it is not working today. I've tried adding content-type as application/x-www-form-urlencoded but it did not work either. When I use curl I'm able to get access token. Also I'm able to get access token using advanced rest client in google chrome. Any ideas why it is returning 400 Bad Request unknown error retry your request?

Imports System.Collections.Specialized
Imports System.Net
Imports System.Text

Module Module1

Sub Main()
    Dim clientId As String = "clientId"
    Dim clientSecret As String = "clientSecret"
    Dim redirectUri As String = "https://test.salesforce.com"
    Dim environment As String = "https://test.salesforce.com"
    Dim tokenUrl As String = ""
    Dim username As String = "username@salesforce.com"
    Dim password As String = "passwordtoken"
    Dim accessToken As String = ""
    Dim instanceUrl As String = ""

    Console.WriteLine("Getting a token")

    tokenUrl = environment + "/services/oauth2/token"
    Dim request As WebRequest = WebRequest.Create(tokenUrl)

    Dim values As NameValueCollection = New NameValueCollection()
    values.Add("grant_type", "password")
    values.Add("client_id", clientId)
    values.Add("client_secret", clientSecret)
    values.Add("redirect_uri", redirectUri)
    values.Add("username", username)
    values.Add("password", password)

    request.Method = "POST"

    Try
        Dim client = New WebClient()
        Dim responseBytes As Byte() = client.UploadValues(tokenUrl, "POST", values)
        Dim response As String = Encoding.UTF8.GetString(responseBytes)
        Console.WriteLine(response)
        Console.ReadKey()
    Catch ex As Exception
        Console.WriteLine(ex.Message)
        Console.WriteLine("Press any key to close")
        Console.ReadKey()
    End Try

End Sub

End Module

回答1:


Well, appearently problem was about TLS version mismatch. All Salesforce sandboxes refuse TLS 1.0 connections. Our vb.net test code was using TLS 1.0 thus returning an error. It would be great if Salesforce would return better error code.

All I needed to do was add a line of code on top of the code block:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11


来源:https://stackoverflow.com/questions/38482611/vb-net-salesforce-post-request-returns-400-bad-request-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!