VB.NET HTTPWEBREQUEST:基础连接已关闭:发送时发生了意外错误



我无法连接到2个URL的1个rest API

icontact.com有2个用于其REST API的URL。

以下代码将适用于第一个URL

" https://app.sandbox.icontact.com/icp/a/"

,但会因以下URL

而失败

https://app.icontact.com/icp/a/

代码详细信息

  • 这是一个控制台应用
  • 该应用程序写在VB.NET .NET框架4.5
  • nuget软件包newtonsoft.json

错误:基础连接已关闭:发送时发生了意外的错误。sendfailure {4}

故障排除:

  • 使用Chrome Arc应用测试REST APPI
  • 确认不是防火墙问题
  • 能够ping网站
  • 沙盒URL能够连接和检索结果
  • 尽管提供的凭据是假的,但您应该能够获得凭据错误而不是关闭连接

代码主模块:

Imports System.Net
Module MainModule
    Sub Main()
        Try
            Dim MyRequest As HttpWebRequest
            MyRequest = IContactManager.BuildJsonRequest
            Dim iContactSecurityInformation As ContactClass
            iContactSecurityInformation = IContactManager.GetiContactSecurityInformation(MyRequest)
        Catch ex As Exception
        End Try
    End Sub
End Module

类:

Imports Newtonsoft.Json.Linq
Imports System.Net
Imports System.IO
Imports System.Web.Script.Serialization
Imports System.Text
Public Class ContactClass
    Public AppId As String
    Public BaseUrl As String
    Public Username As String
    Public Password As String
    Public AccountId As String
    Public ClientFolderId As String
    Public TestMode As Boolean
End Class
Public Class IContactManager
    Public Shared Function BuildJsonRequest() As HttpWebRequest
        Dim uri = New Uri(Convert.ToString(My.Settings.Base_URL + "a/"))
        'Production
        Dim request = DirectCast(WebRequest.Create(uri), HttpWebRequest)
        request.Method = "Get"
        request.Accept = "application/json"
        request.ContentType = "application/json"
        request.Headers.Add("Api-Version", "2.2")
        request.Headers.Add("Api-AppId", "fakeID")
        request.Headers.Add("Api-Username", "FakeUser")
        request.Headers.Add("Api-Password", "FakePassword")
        Return request
    End Function
    Public Shared Function GetiContactSecurityInformation(request As HttpWebRequest) As ContactClass
        Dim Acct As New ContactClass
        Dim a
        Try
            Using response = DirectCast(request.GetResponse(), HttpWebResponse)
                Using reader = New StreamReader(response.GetResponseStream())
                    Dim jsonData = reader.ReadToEnd()
                    Dim serializer = New JavaScriptSerializer()
                    a = serializer.Deserialize(Of ContactClass)(jsonData)
                End Using
            End Using
        Catch exc As System.Net.WebException
            Dim webResponse = TryCast(exc.Response, System.Net.HttpWebResponse)
            If webResponse IsNot Nothing AndAlso webResponse.StatusCode = System.Net.HttpStatusCode.Unauthorized Then
                Console.WriteLine("401")
            Else
                Throw
            End If
        End Try
        Return Acct
    End Function
End Class

我找到了答案,您只需要使用服务点管理器作为无法正常工作的URL

ServicePointManager.SecurityProtocol = SecurityProtocoColType.tls12

相关内容

  • 没有找到相关文章

最新更新