无法将 xml 发送到 Web 服务 - 基础连接已关闭。发送时发生意外错误

Posted

技术标签:

【中文标题】无法将 xml 发送到 Web 服务 - 基础连接已关闭。发送时发生意外错误【英文标题】:Can't send xml to webservice - The underlying connection was closed. An unexpected error occurred on a send 【发布时间】:2015-11-17 10:29:48 【问题描述】:

我正在创建一个应用程序来向 Web 服务提交一些 XML。 问题是我无法与网络服务通信。当我调用“request.GetRequestStream()”时出现此错误:

底层连接已关闭。发生意外错误 发送。

ex.Status = SendFailure 4

这是我正在使用的代码:

Imports System.CodeDom.Compiler
Imports System.CodeDom
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Globalization
Imports System.IO
Imports System.Reflection
Imports System.Web.Services.Protocols
Imports System.Net.WebRequest
Imports System.Net
Imports System.Xml.Serialization
Imports System.Xml
Imports System.Uri
Imports System.Text
Imports System.Security.Policy
Imports System.Security
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography.SHA1CryptoServiceProvider
Imports System.Web.UI.Page
Imports System.Web.Services
Imports System.Windows.Forms.Application
Imports System.Data.OleDb
Imports Microsoft.VisualBasic.Logging



Private Function Send(oRequest As String) As String
         Dim CaminhoCertificado As String = StartupPath + "\certificados\TesteWebServices.pfx"
         Dim SenhaCertificado As String = "*********"

         Dim EnderecoWebService As String = "https://servicos.portaldasfinancas.gov.pt:709/ws/arrendamento"""
         Dim SoapAction As String = "https://servicos.portaldasfinancas.gov.pt/arrendamento/definitions/Arrendamento/registarDadosContratoRequest"


       Try

        Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create(EnderecoWebService), HttpWebRequest)
        Dim cert As New X509Certificate2()
        cert.Import(CaminhoCertificado, SenhaCertificado, X509KeyStorageFlags.DefaultKeySet)



        request.ClientCertificates.Add(cert)

        ''''''''''''''''''''''''''''''''''''''''
        'System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3

        request.ProtocolVersion = HttpVersion.Version10
        request.AllowAutoRedirect = True
        request.UserAgent = "Mozilla/3.0 (compatible; My Browser/1.0)"
        'request.Proxy = System.Net.WebProxy.GetDefaultProxy()
        'request.UseDefaultCredentials = True
        'request.Credentials = CredentialCache.DefaultCredentials
        ''''''''''''''''''''''''''''''''''''''''

        request.Method = "POST"
        request.ContentType = "text/xml; charset=utf-8"
        request.Accept = "text/xml"
        request.KeepAlive = False


        request.Headers.Add("SOAPAction", SoapAction)
        Dim postData As String = oRequest
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
        request.ContentLength = byteArray.Length
''''''''''''''''
            Dim dataStream As Stream = request.GetRequestStream() ''''error is triggered in this line
''''''''''''''''
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()
        Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
        dataStream = response.GetResponseStream()

        Dim reader As New StreamReader(dataStream, Encoding.GetEncoding("windows-1252"))
        Dim responseFromServer As String = reader.ReadToEnd()

        reader.Close()
        dataStream.Close()
        response.Close()
        Return responseFromServer





    Catch ex As WebException
        My.Application.Log.WriteEntry("Error: " & ex.Message & " - " & ex.Status)
        If ex.Status = WebExceptionStatus.ProtocolError Then
            Dim resp As WebResponse = ex.Response
            Dim sr As New StreamReader(resp.GetResponseStream())
            Return sr.ReadToEnd()
        Else
            Return ex.Message & " - " & ex.Status
        End If

    End Try

End Function

目标框架是 .Net Framework 4.5。 如何正确地将 xml 发送到此 Web 服务?

【问题讨论】:

InnerException 中有什么?最好记录 ex.ToString,以获取所有内容,因为 ex.Message 属性非常有限。 ***.com/a/28439582/2319909 好的,所以我在 Windows 中安装了 pfx 文件,现在我得到一个“服务器错误:500”,指向“Dim response As HttpWebResponse”。关于我最初的问题,我想这是一件好事,对吧? 似乎这是一个服务器端问题,而不是原始问题。不过很难说。 【参考方案1】:

您注释掉了 ServicePointManager.SecurityProtocol 分配 - 它可能是必需的,因为连接是 HTTPS - 这可能与 this 重复。

【讨论】:

该行已被注释,因为我已经尝试使用它,但尝试不成功。另外,所有评论的行都在某个时间没有评论,我仍然有同样的问题。谢谢 您是否尝试过 TLS(和其他)SecurityProtocolTypes 以及引用问题中提到的超时设置? 是的,我尝试了所有的安全协议类型也没有成功。【参考方案2】:

这通常与对象的序列化问题有关。确保由于您发布的是 XML 序列化对象,因此它们被定义得很好。 例如

[Serializable]
[XmlRoot(ElementName="Person")]
public class Person

     [XmlElement(ElementName="FirstName")]
     public string Name  get; set; 

     [XmlElement(ElementName="LastName")]
     public string LastName  get; set; 

确保将 XmlRoot 和 Serializable 添加到您的对象中,以便您能够对它们进行序列化和反序列化。

【讨论】:

以上是关于无法将 xml 发送到 Web 服务 - 基础连接已关闭。发送时发生意外错误的主要内容,如果未能解决你的问题,请参考以下文章

无法在Web服务器上启动调试。基础连接已经关闭:接收时发生错误

HTTP基础知识

java web基础知识

Cisco ASA基础

url基础知识

web安全基础-文件上传(含部分upload-labs靶场通关)