5

I'm creating an application to submit some XML to a web-service. The issue is that I can't communicate with the web-service. I'm getting this error, when I call "request.GetRequestStream()":

The underlying connection was closed. An unexpected error occurred on a send.

ex.Status = SendFailure {4}

This is the code that I'm using:

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

The target framework is .Net Framework 4.5. How can I properly send the xml to this webservice?

RSilva
  • 6,753
  • 11
  • 43
  • 49
  • What is in the InnerException? It is better to log ex.ToString, to get everything, as the ex.Message property is pretty limited. – Sam Makin Nov 19 '15 at 11:27
  • 2
    http://stackoverflow.com/a/28439582/2319909 – Sam Makin Nov 19 '15 at 11:34
  • Ok, so I installed the pfx file in Windows and now I get a "server error: 500" pointing to the "Dim response As HttpWebResponse". I guess this is a good thing, regarding my initial issue, right? – RSilva Nov 19 '15 at 12:05
  • Seems like this is a server side issue, as opposed to the original problem. Hard to say though. – Sam Makin Nov 19 '15 at 12:38

2 Answers2

1

You commented out the ServicePointManager.SecurityProtocol assignment - it is probably required as the connection is HTTPS - This may be a duplicate of this.

Community
  • 1
  • 1
Sam Makin
  • 1,526
  • 8
  • 23
  • That line is commented because I already tried to use it, but it was an unsuccessful try. Plus, all the commented lines were somewhere in time not commented and I still had the same issue. Thanks – RSilva Nov 19 '15 at 11:15
  • 1
    Did you try TLS (and other) SecurityProtocolTypes and also the timeout settings mentioned in the referenced question? – Sam Makin Nov 19 '15 at 11:16
  • Yes, I tried all the Security Protocol Types with no success, too. – RSilva Nov 19 '15 at 11:19
0

This is usually related to a serialization issue on the Objects. Make sure that since you are posting XML serialized object they are defined okay. e.g

[Serializable]
[XmlRoot(ElementName="Person")]
public class Person
{
     [XmlElement(ElementName="FirstName")]
     public string Name { get; set; }

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

Make sure the XmlRoot and Serializable are added to your objects so you can be able to serialize and desirialize them.

befree2j
  • 361
  • 5
  • 11