How to communicate with SOAP webservice

Asked

Viewed 340 times

1

I am trying to communicate with a SOAP Webservice. I was able to communicate using SOAPUI as image:

inserir a descrição da imagem aqui

I am developing this communication in c# as follows:

try
        {
            var service = new com.nexxera.flnws001qae.NexxeraWSv2ImplService();

            service.RequestSoapContext.Security.Tokens
                    .Add(new UsernameToken(Properties.Settings.Default.USUARIOWS, Properties.Settings.Default.SENHAWS, PasswordOption.SendPlainText));

            var FileName = System.IO.Path.GetFileName(currentFilePath);

            service.RequestSoapContext.Attachments.Add(new
                Microsoft.Web.Services2.Attachments.Attachment(FileName,
                    "application/octet-stream", currentFilePath));

            service.RequestSoapContext.Add("text/plain", new ContentType());

            var c = new StreamReader(currentFilePath).ReadToEnd();

            var fs = new com.nexxera.flnws001qae.fileWrapper
            {
                filename = currentFilePath.Split('\\').Last(),
                content = currentFilePath.Split('\\').Last()
            };
            var arqq = new com.nexxera.flnws001qae.uploadFilev2
            {
                destination = "LARIND.BANCOS",
                file = fs
            };

            var result = service.uploadFile(arqq);

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message.ToString());
        }

I’m making the following mistake:

 {"Unsupported content type: application/dime"}   

I cannot set the Contenttype option:

service.RequestSoapContext.ContentType = "text/plain";

I tried to use the method passed by Carlos, called the method:

var envelope = new XmlDocument();
envelope.Load("C:\\Nexxera\\teste.xml");
GetResultservice(envelope, "http://flnws001qae.nexxera.com:80/nexxeraws/v2/SkylineWSv2");

content of the texte.xml:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:NexxeraWS">
<soapenv:Header/>
<soapenv:Body>
  <urn:uploadFile>
     <!--Optional:-->
     <file>
        <filename>C:\Nexxera\log_0615.txt</filename>
        <content>C:\Nexxera\log_0614.txt</content>
     </file>
     <!--Optional:-->
     <destination>LARIND.BANCOS</destination>
  </urn:uploadFile>

Returns me error:

O servidor remoto retornou um erro: (500) Erro Interno do Servidor.

Following Carlos' example, implement this way:

 public string ProcessAttachment(string fileInput)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://flnws001qae.nexxera.com:80/nexxeraws/v2/SkylineWSv2");
        req.Method = "POST";
        req.ProtocolVersion = HttpVersion.Version11;
        req.Headers.Add("Accept-Encoding", "gzip,deflate");
        req.ContentType = "multipart/related; type=\"text/xml\"; start=\"teste\"; boundary=\"----=_Part_72_348989292.1565031692584\"";
        req.Headers.Add("SOAPAction", "\"\"");
        req.Headers.Add("MIME-Version", "1.0");
        //req.ContentLength = 1854;
        req.Host = "flnws001qae.nexxera.com:80";
        req.UserAgent = "Apache-HttpClient/4.1.1 (java 1.5)";        
        req.KeepAlive = true; 

        System.Net.ServicePointManager.Expect100Continue = false;
        Stream memStream = new System.IO.MemoryStream();
        FileStream fileStream = new FileStream(fileInput, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();
        Stream stm = req.GetRequestStream();
        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        stm.Write(tempBuffer, 0, tempBuffer.Length);
        stm.Close();
        HttpWebResponse resp = null;
        resp = (HttpWebResponse)req.GetResponse();
        stm = resp.GetResponseStream();
        StreamReader r = new StreamReader(stm);
        return r.ReadToEnd();
    }

I added the Arq.xml file

            ------=_Part_72_348989292.1565031692584
            Content-Type: text/xml; charset=UTF-8
            Content-Transfer-Encoding: 8bit
            Content-ID: teste

            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:NexxeraWS">
               <soapenv:Header>
                    <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
                        <wsse:UsernameToken wsu:Id="UsernameToken-C3491A557C4FE15638156503169258275">
                            <wsse:Username>homologacao</wsse:Username>
                            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">test</wsse:Password>
                            <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">vbCcpxa/p0Ceton7RevESw==</wsse:Nonce>
                            <wsu:Created>2019-08-05T19:01:32.582Z</wsu:Created>
                        </wsse:UsernameToken>
                    </wsse:Security>
                </soapenv:Header>
                <soapenv:Body>
                  <urn:uploadFile>
                     <!--Optional:-->
                     <file>
                        <filename>log_0805.txt</filename>
                        <content>log_0614.txt</content>
                     </file>
                     <!--Optional:-->
                     <destination>LARIND.BANCOS</destination>
                  </urn:uploadFile>
                </soapenv:Body>
            </soapenv:Envelope>
            ------=_Part_72_348989292.1565031692584
            Content-Type: text/plain; charset=us-ascii; name=log_0614.txt
            Content-Transfer-Encoding: 7bit
            Content-ID: <log_0614.txt>
            Content-Disposition: attachment; name="log_0614.txt"; filename="log_0614.txt"

            "LA09"; "33007110138"; "110273"; "S0007"; "785522"; "EFETUADA "; "CMPCTCRC"; "00"; "11/04/2019"; "13:06:50"; "       5155******33"; 89; 01; "5155";
            ------=_Part_72_348989292.1565031692583--

Which would be the best way to update this.xml file, because for each file I will have different information such as name, size and different information. Also has the "----=Part" that should change as my log information...txt.

  • I think you lack important information in your question or in the title that is "using attachment"

2 answers

0

Do it this way:

1º Create a structure with request data, example:

private StringContent MontarEnvelope()
{
    var envelope = $@"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:sfin=""urn:NexxeraWS"">
    <soapenv:Header/>
    <soapenv:Body>
        <sfin:empty/>
    </soapenv:Body>
    </soapenv:Envelope>";
    return new StringContent(envelope, Encoding.UTF8, "text/xml");
}

2nd Create your call method, example:

static readonly HttpClient _httpClient = new HttpClient();

public async Task<string> Consultar()
{
    string url = "http://flnws001qae.nexxera.com:80/nexxeraws/v2/SkylineWSv2";      
    var content = MontarEnvelope();
    using (var response = await _httpClient.PostAsync(url, content))
    {
        var soapResult = await response.Content.ReadAsStringAsync();
        return soapResult;
    }
}

var resultado = await Consultar();

This is the way, the above example is asynchronous.

-2

Good morning. Follow example:

public XmlDocument GetResultservice(XmlDocument envelope, string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                byte[] buffer2 = Encoding.ASCII.GetBytes(envelope.InnerXml);                
                request.Timeout = 900;
                request.ContentType = "text/xml; charset=utf-8";
                request.Method = "POST";
                request.ContentLength = buffer2.Length;
                Stream PostData = request.GetRequestStream();
                PostData.Write(buffer2, 0, buffer2.Length);
                PostData.Close();
                WebResponse responsePost = (HttpWebResponse)request.GetResponse();
                Stream istreamPost = responsePost.GetResponseStream();
                XmlDocument res = new XmlDocument();
                using (StreamReader rd = new StreamReader(istreamPost, System.Text.Encoding.ASCII))
                {
                    res.LoadXml(rd.ReadToEnd().Replace("'", "''"));
                }
                istreamPost.Close();
                responsePost.Close();
                PostData.Close();
                request = null;
                return res;
            }catch(Exception e)
            {
                throw e;
            }
        }
  • Carlos Soares, I didn’t understand your code, where and how to use this code in my application?

  • Good morning Tiago, all right? This is called Soap without adding a service reference.

  • All right Carlos and with Voce? I’m having difficulties in using your method, I put the connection attempt at the end of the question.

  • All right Tiago, you managed to do is called in a test tool, like Postman? .

  • Carlos implemented his code. At first it worked, but I have another question, as asked in the question. What would be the best way to update this file?

  • Opa! This file is a return from webservice?

Show 1 more comment

Browser other questions tagged

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