C#, The underlying link has been closed: Unexpected error while sending

Asked

Viewed 365 times

2

I’m trying to communicate by webservice and always gives me the error: "Underlying connection closed: Unexpected error while sending."

The method I’m using is this:

private void GetATCode(string pSoapFile, string pWebService, string pServiceAction, string pCertifPath, string pCertifPassword)
{
    string EnderecoWebService = pWebService;
    string CaminhoCertificado = pCertifPath;
    string SenhaCertificado = pCertifPassword;
    try {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(EnderecoWebService);
        request.Headers.Add("SOAPAction", pServiceAction);
        X509Certificate2 cert = new X509Certificate2();
        cert.Import(CaminhoCertificado, SenhaCertificado, X509KeyStorageFlags.DefaultKeySet);
        request.ClientCertificates.Add(cert);
        request.Method = "POST";
        request.ContentType = "text/xml; charset=utf-8";
        request.Accept = "text/xml";
        string postData = pSoapFile;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = byteArray.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        dataStream.Close();
        response.Close();
        TextBox2.Text = responseFromServer;
    } catch (WebException ex) 
    {
        if (ex.Status == WebExceptionStatus.ProtocolError) 
        {
            WebResponse resp = ex.Response;
            StreamReader sr = new StreamReader(resp.GetResponseStream());
            TextBox2.Text = sr.ReadToEnd();
        } 
        else 
        {
            TextBox2.Text = ex.Message;
        }
    }

Can someone give me a hand?

  • Which line gives the error? You want to communicate with an API?

  • When I debug, stopping line by line on this line: "Stream Datastream = request.Getrequeststream();" jumps to the end...

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.