如何使xml内容与内容的HttpClient's
PostAsync
操作兼容,并在何处为headers
指定Content-Type = application/xml
。
错误 - >无法将字符串转换为HttpContent
public async Task GetCustomersAsync(string firstname, string lastname)
{
using (var client = new HttpClient())
{
var content = "<soapenv:Envelope xmlns:xsi...";
var response = await client.PostAsync("https://domain.com/scripts/WebObj.exe/Client.woa/2/ws/ABC", content);
var responseString = await response.Content.ReadAsStringAsync();
}
}
答案 0 :(得分:1)
我的猜测是你想要做的是以下几点:
public async Task<string> GetCustomersAsync(string firstname, string lastname)
{
using (var client = new HttpClient())
{
var content = new StringContent("<soapenv:Envelope xmlns:xsi...", Encoding.UTF8, "application/xml");;
var response = await client.PostAsync("https://example.com/scripts/WebObj.exe/Client.woa/2/ws/ABC", content);
return await response.Content.ReadAsStringAsync();
}
}
OR
using (var request = new HttpRequestMessage { RequesteUri = new Uri("POST_URL"), Method = HttpMethod.Post })
{
var content = new StringContent("<soapenv:Envelope xmlns:xsi...");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
}
您可以refer here获取有关可以创建和传递的其他内容类型的更多信息。
答案 1 :(得分:1)
要专门请求xml内容作为响应,您必须在内容的标题中定义内容类型。在内容标题的ContentType属性中解析并设置MediaTypeHeaderValue。这是代码的完整示例;
using (var client = new HttpClient())
{
var content = new StringContent(messageToPOST, Encoding.UTF8, "text/xml");
content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml");
response = await client.PostAsync(_uri, content);
responseMsg = await response.Content.ReadAsStringAsync();
}
可以将请求作为响应返回的responseMsg属性解析为字符串,或者使用诸如
这样的表达式转换为xml并验证为xmlXDocument xdoc = XDocument.Parse(responseMsg);
string xmlAsString = xdoc.ToString();