Webservice does not accept xml file

0

I am generating an XML, and sending to webservice , and it always returns me the same error, Error 500, however this error is very vague, I was able to have the following return on error:

  

: ServerCould not parse content   type: javax.mail.internet.ParseException: Expected parameter name, got   "/"

Here's how I'm trying to send:

public static MemoryStream stringToStream(string dados)
    {
        MemoryStream memoryStream;
        try
        {
            byte[] byteArray = new byte[dados.Length];
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byteArray = encoding.GetBytes(dados);
            memoryStream = new MemoryStream(byteArray);
            memoryStream.Seek(0, SeekOrigin.Begin);
        }
        catch (Exception ex)
        {
            return null;
        }

        return memoryStream;
    }

    private void montaEnvelope(HttpWebRequest webRequest, XmlDocument document, string numero)
    {
        string soapEnvelope = string.Empty;


        //soapEnvelope += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.issweb.fiorilli.com.br/\" xmlns:xd=\"http://www.w3.org/2000/09/xmldsig#\">";
        soapEnvelope += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:e=\"http://www.betha.com.br/e-nota-contribuinte-ws\">";
        //soapEnvelope += "<soapenv:Header/><soapenv:Body><ws:gerarNfse>";
        soapEnvelope += "<soapenv:Header/><soapenv:Body><e:gerarNfse><nfseCabecMsg>";
        soapEnvelope += "<cabecalho xmlns=\"http://www.betha.com.br/e-nota-contribuinte-ws\" versao=\"2.02\"><versaoDados>2.02</versaoDados></cabecalho></nfseCabecMsg><nfseDadosMsg>";

           soapEnvelope += document.LastChild.OuterXml.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", string.Empty);
        //soapEnvelope += "<username>01001001000113</username><password>123456</password></ws:gerarNfse></soapenv:Body></soapenv:Envelope>";
        soapEnvelope += "</nfseDadosMsg></e:gerarNfse></soapenv:Body></soapenv:Envelope>";
        //soapEnvelope += "</e:gerarNfse></soapenv:Body></soapenv:Envelope>";
        MemoryStream stream = stringToStream(soapEnvelope);
        webRequest.ContentLength = stream.Length;
        Stream requestStream = webRequest.GetRequestStream();
        stream.WriteTo(requestStream);

        document.LoadXml(soapEnvelope);
        document.PreserveWhitespace = false;

        document.Save(@"E:\NFSe-" + "RPS" + numero.ToString().PadLeft(15, '0') + ".xml");
        System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load("E:\NFSe-" + "RPS" + numero.ToString().PadLeft(15, '0') + ".xml");
        doc.Save("E:\NFSe-" + "RPS" + numero.ToString().PadLeft(15, '0') + ".xml", System.Xml.Linq.SaveOptions.DisableFormatting);


        this.XmlDocNFSe = document;
    }

    private static string getSoapResponse(HttpWebRequest webRequest)
    {
        string soapResult = string.Empty;

        WebResponse webResponse = webRequest.GetResponse();
        StreamReader rd = new StreamReader(webResponse.GetResponseStream());
        soapResult = rd.ReadToEnd();

        XmlDocument xmlResponse = new XmlDocument();
        xmlResponse.LoadXml(soapResult);
        XmlNode responseNode = xmlResponse.LastChild.LastChild.FirstChild;

        XmlNamespaceManager ns = new XmlNamespaceManager(xmlResponse.NameTable);
        ns.AddNamespace("ns2", "http://www.abrasf.org.br/nfse.xsd");
        XmlNode codigo = xmlResponse.SelectSingleNode("//ns2:Codigo", ns);
        XmlNode mensagem = xmlResponse.SelectSingleNode("//ns2:Mensagem", ns);
        XmlNode correcao = xmlResponse.SelectSingleNode("//ns2:Correcao", ns);
        XmlNode numero = xmlResponse.SelectSingleNode("//ns2:Numero", ns);
        XmlNode codigoVerificacao = xmlResponse.SelectSingleNode("//ns2:CodigoVerificacao", ns);
        XmlNode data = xmlResponse.SelectSingleNode("//ns2:DataEmissao", ns);
        XmlNode outras = xmlResponse.SelectSingleNode("//ns2:Outras", ns);
        foreach (XmlNode node in xmlResponse.SelectNodes("//ns2:InfNfse", ns))
        {
            Id = (node.Attributes["Id"].Value);
        }
        try
        {
            cod = codigo.InnerText;
            msgm = mensagem.InnerText;
            cor = correcao.InnerText;
        }
        catch
        {
            Numero = numero.InnerText;
            CodigoVerificacao = codigoVerificacao.InnerText;
        }
        return responseNode.InnerXml;

    }

    private static HttpWebRequest getWebRequest(string url, string method)
    {
        HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
        webRequest.Timeout = 100000;
        webRequest.Headers.Add("SOAPAction", method);
        webRequest.ContentType = "text/xml; //charset=\"utf-8\"";
        webRequest.Accept = "text/xml";
        webRequest.Method = "POST";
        return webRequest;
    }


private string post(string url, string method, string xml, X509Certificate2 certificate, string numero)
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(xml);

            HttpWebRequest webRequest = getWebRequest(url, method);
            webRequest.Proxy = HttpWebRequest.GetSystemWebProxy();
            webRequest.UseDefaultCredentials = true;
            webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
            WebProxy myProxy = new WebProxy();
            Uri myUri = new Uri("http://192.168.0.3:3128");
            myProxy.Address = myUri;
            myProxy.Credentials = CredentialCache.DefaultCredentials;
            //webRequest.Proxy = new WebProxy(MyProxyHostString, MyProxyPort);
            webRequest.Proxy = myProxy;
            webRequest.ClientCertificates.Add(certificate);

            montaEnvelope(webRequest, doc, numero);
            return getSoapResponse(webRequest);
        }

        catch (WebException webex)
        {
            WebResponse errResp = webex.Response;
            using (Stream respStream = errResp.GetResponseStream())
            {
                StreamReader reader = new StreamReader(respStream);
                msgm = reader.ReadToEnd();
                cod = "Erro";
            }
            return msgm;
        }
        //}
        //catch (Exception ex)
        //{
        //    return null;
        //}
    }

I can not get another feedback, what am I doing wrong? I'll put the xml.

<?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:e="http://www.betha.com.br/e-nota-contribuinte-ws"><soapenv:Header /><soapenv:Body><e:gerarNfse><nfseCabecMsg><cabecalho xmlns="http://www.betha.com.br/e-nota-contribuinte-ws" versao="2.02"><versaoDados>2.02</versaoDados></cabecalho></nfseCabecMsg><nfseDadosMsg><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:e="http://www.betha.com.br/e-nota-contribuinte-ws"><soapenv:Header /><soapenv:Body><e:gerarNfse><nfseCabecMsg><cabecalho xmlns="http://www.betha.com.br/e-nota-contribuinte-ws" versao="2.02"><versaoDados>2.02</versaoDados></cabecalho></nfseCabecMsg><nfseDadosMsg><GerarNfseEnvio xmlns="http://www.betha.com.br/e-nota-contribuinte-ws"><Rps><InfDeclaracaoPrestacaoServico Id="RPS000000000008963"><Rps><IdentificacaoRps><Numero>8963</Numero><Serie>999</Serie><Tipo>1</Tipo></IdentificacaoRps><DataEmissao>2018-12-17</DataEmissao><Status>1</Status></Rps><Competencia>2018-12-17</Competencia><Servico><Valores><ValorServicos>29</ValorServicos><ValorDeducoes>0.00</ValorDeducoes><ValorIss>0.87</ValorIss><Aliquota>3</Aliquota><DescontoIncondicionado>0</DescontoIncondicionado><DescontoCondicionado>0</DescontoCondicionado></Valores><IssRetido>2</IssRetido><ItemListaServico>0107</ItemListaServico><Discriminacao>Descricao 62</Discriminacao><CodigoMunicipio>0</CodigoMunicipio><ExigibilidadeISS>1</ExigibilidadeISS><MunicipioIncidencia>3107109</MunicipioIncidencia></Servico><Prestador><CpfCnpj><Cnpj>07652413000108</Cnpj></CpfCnpj><InscricaoMunicipal>5467630</InscricaoMunicipal></Prestador><Tomador><IdentificacaoTomador><CpfCnpj><Cpf>08297163008</Cpf></CpfCnpj></IdentificacaoTomador><RazaoSocial>Teste Mariana</RazaoSocial><Endereco><Endereco>RUA JARBAS PIMENTA</Endereco><Numero>514</Numero><Complemento>complemento cobrancaaeAaO</Complemento><Bairro>NOVA ERA</Bairro><CodigoMunicipio>3504800</CodigoMunicipio><Uf>SP</Uf><Cep>37170000</Cep></Endereco><Contato><Telefone>3538511836</Telefone><Email>[email protected]</Email></Contato></Tomador><RegimeEspecialTributacao>1</RegimeEspecialTributacao><OptanteSimplesNacional>1</OptanteSimplesNacional><IncentivoFiscal>1</IncentivoFiscal></InfDeclaracaoPrestacaoServico><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><Reference URI="#RPS000000000008963"><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /><Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>XXvtJY4dUMxIcMWw+yUbSHNkfUE=</DigestValue></Reference></SignedInfo><SignatureValue>XoWPqLsjsojfsjFs6ZXXc/bGb0Vy7EcFc5QOe/ja88Nhi3dKV76LCogTz4GjYD0tByovmXixCfez3sSuyijeTTryj8vTAsQKBgDj/PFD08W/fJsE+zmOPxYCqAE2m2yBZD++afT3DOYDqYxkwGpF/o5YSaMAA3G1ilUvfPUqlq3VmT6NIiD1ffvZsh02TpTZMz35JTb0rptX/5tsswAaWJTwrMAljY23iibD4Pkl+fGXFKDHXWdHv1XSiSvSSK3Niost02OxqfxwWQedspFGgXnmpx3fee7qSyHPKavZu64KUvy8jNDKJkUNYg/V/DAe3ShQPbZrbUW6KemN6BM76A==</SignatureValue><KeyInfo><X509Data><X509Certificate>MIIIETCCBfmgAwIBAgIIU+7gQoD+KpcwDQYJKoZIhvcNAQELBQAwdDELMAkGA1UEBhMCQlIxEzARBgNVBAoTCklDUC1CcmFzaWwxNjA0BgNVBAsTLVNlY3JldGFyaWEgZGEgUmVjZWl0YSBGZWRlcmFsIGRvIEJyYXNpbCAtIFJGQjEYMBYGA1UEAxMPQUMgRE9DQ0xPVUQgUkZCMB4XDTE3MDMzMDEzMTMxMFoXDTIwMDMzMDEzMTMxMFowgeMxCzAJBgNVBAYTAkJSMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMQswCQYDVQQIEwJNRzEWMBQGA1UEBxMNQk9BIEVTUEVSQU5DQTE2MDQGA1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ofSFmuUocN8i7wbWuHb/bz4fIOLLEuJZRRUG8LO2w86gF3PO9U9UURYO8FWbeFtUIuXBEkUmSXdT6Nhf4b1zI2nu7ygN3HnkZR2bnCkUefOQBE47U7K3b3jwEVu0yKEKAXTtu8nYZ1WoKikkIkp/9+WpFUYZcy+cz/xixYO97cvlWpKq9IJmx5OPBBXBOMoxSqrLFs/Z9QdFwCmCGJo0m8qO4qRTXcvG0TXbI45+xK/WwArpEzBiY8beYcN+glsjlhoO+jqv/zhOKv+n66CRINgEDV+PCs535JEUw=</X509Certificate></X509Data></KeyInfo></Signature></Rps></GerarNfseEnvio></nfseDadosMsg></e:gerarNfse></soapenv:Body></soapenv:Envelope></nfseDadosMsg></e:gerarNfse></soapenv:Body></soapenv:Envelope>
    
asked by anonymous 17.12.2018 / 11:59

1 answer

1

You're making it too complicated to use this service. If you allow me, check out the documentation at: link . There are manuals and examples of xmls expected.

Here's a new approach to consume this service:

Add the service reference in visual studio to wsdl: link

In% w_through% right click on the project and go to Soluction Explorer then Add . In% with% enter the WSDL URL and click% with%. In Service Reference enter the desired name. Address Click Go .

After this, see the example below on how to call the webservice: (obs: of course it is simplified for testing, demonstrating the expected xml as per the documentation.)

using (var cli = new wsNfse.NfseWSClient())
            {
                string _nfseCabecMsg = $@"
                     < cabecalho xmlns = ""http://www.betha.com.br/e-nota-contribuinte-ws"" versao = ""2.02"" >< versaoDados > 2.02 </ versaoDados ></ cabecalho >
                    ";
                string _nfseDadosMsg = $@"
                    <GerarNfseEnvio xmlns = ""http://www.betha.com.br/e-nota-contribuinte-ws"">
                        <Rps>
                            <InfDeclaracaoPrestacaoServico  Id=""lote"">
                                <Rps>
                                    <IdentificacaoRps>
                                        <Numero></Numero>
                                        <Serie></Serie>
                                        <Tipo></Tipo>
                                    </IdentificacaoRps>
                                    <DataEmissao></DataEmissao>
                                    <Status></Status>
                                    <RpsSubstituido>
                                        <Numero></Numero>
                                        <Serie></Serie>
                                        <Tipo></Tipo>
                                    </RpsSubstituido>
                                </Rps>
                                <Competencia></Competencia>
                                <Servico>
                                    <Valores>
                                        <ValorServicos></ValorServicos>
                                        <ValorDeducoes></ValorDeducoes>
                                        <ValorPis></ValorPis>
                                        <ValorCofins></ValorCofins>
                                        <ValorInss></ValorInss>
                                        <ValorIr></ValorIr>
                                        <ValorCsll></ValorCsll>
                                        <OutrasRetencoes></OutrasRetencoes>
                                        <ValorIss></ValorIss>
                                        <Aliquota></Aliquota>
                                        <DescontoIncondicionado></DescontoIncondicionado>
                                        <DescontoCondicionado></DescontoCondicionado>   
                                    </Valores>
                                    <IssRetido></IssRetido>
                                    <ResponsavelRetencao></ResponsavelRetencao>
                                    <ItemListaServico></ItemListaServico>
                                    <CodigoCnae></CodigoCnae>
                                    <CodigoTributacaoMunicipio></CodigoTributacaoMunicipio>
                                    <Discriminacao></Discriminacao>
                                    <CodigoMunicipio></CodigoMunicipio>
                                    <CodigoPais></CodigoPais>
                                    <ExigibilidadeIss></ExigibilidadeIss>
                                    <MunicipioIncidencia></MunicipioIncidencia>
                                    <NumeroProcesso></NumeroProcesso>
                                </Servico>
                                <Prestador>
                                    <CpfCnpj>
                                        <Cnpj></Cnpj>
                                    </CpfCnpj>
                                    <InscricaoMunicipal></InscricaoMunicipal>
                                </Prestador>
                                <Tomador>
                                    <IdentificacaoTomador>
                                        <CpfCnpj>
                                            <Cnpj></Cnpj>
                                        </CpfCnpj>
                                        <InscricaoMunicipal></InscricaoMunicipal>               
                                    </IdentificacaoTomador>
                                    <RazaoSocial></RazaoSocial>
                                    <Endereco>
                                        <Endereco></Endereco>
                                        <Numero></Numero>
                                        <Complemento></Complemento>
                                        <Bairro></Bairro>
                                        <CodigoMunicipio></CodigoMunicipio>
                                        <Uf></Uf>
                                        <CodigoPais></CodigoPais>
                                        <Cep></Cep>
                                    </Endereco>
                                    <Contato>
                                        <Telefone></Telefone>
                                        <Email></Email>
                                    </Contato>
                                </Tomador>
                                <Intermediario>
                                    <IdentificacaoIntermediario>
                                        <CpfCnpj>
                                            <Cnpj></Cnpj>
                                        </CpfCnpj>
                                        <InscricaoMunicipal></InscricaoMunicipal>               
                                    </IdentificacaoIntermediario>
                                    <RazaoSocial></RazaoSocial>
                                </Intermediario>
                                <ConstrucaoCivil>
                                    <CodigoObra></CodigoObra>
                                    <Art></Art>
                                </ConstrucaoCivil>
                                <RegimeEspecialTributacao></RegimeEspecialTributacao>
                                <OptanteSimplesNacional></OptanteSimplesNacional>
                                <IncentivoFiscal></IncentivoFiscal>
                            </InfDeclaracaoPrestacaoServico>
                        </Rps>
                    </GerarNfseEnvio>
                ";                

                var retorno = cli.GerarNfse(new wsNfse.GerarNfse { nfseCabecMsg = _nfseCabecMsg, nfseDadosMsg = _nfseDadosMsg });
            }

Check the return string variable!

You could also create classes according to the XML objects and serialize the objects to fill in the string input parameters and the object return string. Here are two useful functions for this:

/// <summary>
/// Serializa um objeto para uma string no formato XML apartir do objeto referênciado.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">Objeto</param>
/// <example>string xmlString = meuObj.XmlSerialize();</example>
/// <returns>String em formato XML do objeto referênciado</returns>
public static string ToXml<T>(this T value)
{
    if (value == null)
        return string.Empty;

    var xmlserializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using (var stringWriter = new StringWriter())
    {
        using (var writer = System.Xml.XmlWriter.Create(stringWriter))
        {
            xmlserializer.Serialize(writer, value);
            return stringWriter.ToString();
        }
    }
}

/// <summary>
/// Deserializa uma string em formato XML em um objeto do tipo especificado.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">XML string</param>
/// <example>MinhaClasse obj = xmlString.XmlToObject<MinhaClasse>();</example>
/// <returns>Objeto do tipo especificado</returns>
public static T XmlToObject<T>(this string value)
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
    using (StringReader rdr = new StringReader(value))
    {
        return (T)serializer.Deserialize(rdr);
    }
}

I hope I have helped!

    
17.12.2018 / 20:59