HttpClient & SOAP (C#)

前端 未结 1 1066
猫巷女王i
猫巷女王i 2020-12-09 08:07

I\'m trying to use the HttpClient class to send a SOAP message:

Doing so with REST seems easy (code from here) :

using System;
using System.Net.Http;
u         


        
相关标签:
1条回答
  • 2020-12-09 08:37

    I needed to do this myself and since I couldn't find any answers online, here's what I worked out. This uses a simple SOAP calculator service with an 'Add' method that takes two numbers and returns the sum.

    public async Task<int> AddNumbersAsync(Uri uri, int a, int b)
    {
        var soapString = this.ConstructSoapRequest(a, b);
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("SOAPAction", "http://CalculatorService/ICalculatorService/Add");
            var content = new StringContent(soapString, Encoding.UTF8, "text/xml");
            using (var response = await client.PostAsync(uri, content))
            {
                var soapResponse = await response.Content.ReadAsStringAsync();
                return this.ParseSoapResponse(soapResponse);
            }
        }
    }
    
    private string ConstructSoapRequest(int a, int b)
    {
        return String.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
        <s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
            <s:Body>
                <Add xmlns=""http://CalculatorService/"">
                    <a>{0}</a>
                    <b>{1}</b>
                </Add>
            </s:Body>
        </s:Envelope>", a, b);
    }
    
    private int ParseSoapResponse(string response)
    {
        var soap = XDocument.Parse(response);
        XNamespace ns = "http://CalculatorService/";
        var result = soap.Descendants(ns + "AddResponse").First().Element(ns + "AddResult").Value;
        return Int32.Parse(result);
    }
    
    0 讨论(0)
提交回复
热议问题