[英]HttpClient & SOAP (C#)
我正在嘗試使用 HttpClient 類發送 SOAP 消息:
使用 REST 這樣做似乎很容易(來自此處的代碼):
using System;
using System.Net.Http;
using System.Json;
namespace ConsoleApplication39
{
class Program
{
static void Main(string[] args)
{
HttpClient proxy = new HttpClient();
proxy.GetAsync("http://localhost:14892/api/Bloggers").ContinueWith((r) =>
{
HttpResponseMessage response = r.Result;
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(a)=>
{
foreach(var w in a.Result)
{
Console.WriteLine(w.ValueOrDefault("Name").ToString());
Console.WriteLine(w.ValueOrDefault("Intrest").ToString());
}
});
});
Console.ReadKey(true);
}
}
}
我想用 SOAP 做類似的事情。
我有主機( http://opensearch.addi.dk/2.2/ )和要 POST 的 SOAP 消息:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://oss.dbc.dk/ns/opensearch">
<SOAP-ENV:Body>
<ns1:searchRequest>
<ns1:query>dc.title=zorro AND dc.type=bog</ns1:query>
<ns1:agency>100200</ns1:agency>
<ns1:profile>test</ns1:profile>
<ns1:start>1</ns1:start>
<ns1:stepValue>10</ns1:stepValue>
</ns1:searchRequest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
...但如何發送呢?
我承認這是我用過的第一個 SOAP Web 服務,所以我可能不知道我在做什么,但最簡單的形式可能是這樣的:
HttpClient hc = new HttpClient();
hc.BaseAddress = new Uri("http://opensearch.addi.dk/2.2/");
HttpContent content = *... something*
HttpResponseMessage rm = await hc.PostAsync("http://opensearch.addi.dk/2.2/", content);
我認為 SOAP 消息應該以某種方式通過 HttpContent.Create(..) 之類的 HttpContent 靜態方法創建,但我無法讓它工作......
我知道這是一個愚蠢的問題,但我仍然需要幫助:)!
蒂...
我需要自己做這件事,因為我在網上找不到任何答案,這就是我解決的問題。 這使用了一個簡單的 SOAP 計算器服務和一個“Add”方法,該方法接受兩個數字並返回總和。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.