我一直在尝试使用 .Net Framework 4.7 中的 HTTPClient 对象来创建简单的 SOAP 请求。我已经使用了 Postman 中的参数,它工作得很好。这是我的代码:
string url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso";
//SOAP envelope string
string xmlSOAP =
@"<? xml version = ""1.0"" encoding = ""utf-8"" ?>
< soap : Envelope xmlns: soap = ""http://schemas.xmlsoap.org/soap/envelope/"" >
< soap:Body >
< ListOfContinentsByName xmlns = ""http://www.oorsprong.org/websamples.countryinfo"">
</ ListOfContinentsByName >
</ soap:Body >
</ soap:Envelope >";
HttpClient httpClient = new HttpClient();
HttpContent httpContent = new StringContent(xmlSOAP);
HttpResponseMessage response;
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, url);
req.Headers.Add("SOAPAction", "");
req.Method = HttpMethod.Post;
req.Content = httpContent;
req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml; charset=utf-8");
// Here you will get the Reponse from service
response = await httpClient.SendAsync(req);
// Converting the response into text format
var responseBodyAsText = await response.Content.ReadAsStringAsync();
知道为什么这在邮递员中有效但不使用 HTTPClient 吗?我从这里的微软示例中引用了这一点(https://social.msdn.microsoft.com/Forums/windowsapps/en-US/15e0c692-c47c-443c-b96d-5c4f77e7ed66/how-to-sendreceive-soap-request-and-response-using-c-in- windows-phone-8?forum=wpdevelop https://social.msdn.microsoft.com/Forums/windowsapps/en-US/15e0c692-c47c-443c-b96d-5c4f77e7ed66/how-to-sendreceive-soap-request-and-response-using-c-in-windows-phone-8?forum=wpdevelop).
您的代码看起来不错并且应该可以工作。看来 API 服务器现在已关闭。
这是相同的代码,经过一些修复和改进,使其变得稳定
public class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
string url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso";
string xmlSOAP = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<ListOfContinentsByName xmlns=""http://www.oorsprong.org/websamples.countryinfo""/>
</soap:Body>
</soap:Envelope>";
try
{
string result = await PostSOAPRequestAsync(url, xmlSOAP);
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
private static async Task<string> PostSOAPRequestAsync(string url, string text)
{
using (HttpContent content = new StringContent(text, Encoding.UTF8, "text/xml"))
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url))
{
request.Headers.Add("SOAPAction", "");
request.Content = content;
using (HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
//response.EnsureSuccessStatusCode(); // throws an Exception if 404, 500, etc.
return await response.Content.ReadAsStringAsync();
}
}
}
}
也许你还可以填写SOAPAction
例如和url
,但这取决于服务器要求。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)