VB.NET - Salesforce POST请求返回400错误请求错误

时间:2016-07-20 13:25:22

标签: vb.net oauth visual-studio-2015 http-post salesforce

注意:我之前从未编写过vb.net代码。我已经搜索了一个解决方案,但没有找到任何有效的方法。

我试图从Salesforce获取访问令牌。 以下代码仅在昨天工作。我不知道为什么它今天不起作用。我尝试将内容类型添加为 application / x-www-form-urlencoded ,但它也无效。当我使用curl时,我能够获得访问令牌。此外,我还可以使用Google Chrome中的高级休息客户端获取访问令牌。有任何想法,为什么它返回 400错误请求 未知错误重试您的请求

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 个答案:

答案 0 :(得分:10)

嗯,显然问题是关于TLS版本不匹配。所有Salesforce沙箱都拒绝TLS 1.0连接。我们的vb.net测试代码使用的是TLS 1.0,因此返回错误。如果Salesforce会返回更好的错误代码,那就太好了。

我需要做的就是在代码块的顶部添加一行代码:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11