简体   繁体   English

使用HttpClient调用xml内容

[英]Post call for xml content using HttpClient

How to make xml content compatible with HttpClient's PostAsync operation for the content and where do you specify the headers for Content-Type = application/xml . 如何使xml内容与HttpClient's内容HttpClient's PostAsync操作兼容,以及在何处指定Content-Type = application/xmlheaders

Error -> Cannot convert string to HttpContent 错误 - >无法将字符串转换为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();
        }
    }

My guess is what you want to do is the following: 我的猜测是你想要做的是以下几点:

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");
}

You can refer here to more information about other Content types that can be created and passed. 您可以在此处参考有关可以创建和传递的其他内容类型的更多信息。

To specifically request xml content in response you must define the content type in the header of the content. 要在响应中专门请求xml内容,您必须在内容的标题中定义内容类型。 The MediaTypeHeaderValue is parsed and set in the ContentType property of the content Headers. MediaTypeHeaderValue在内容标头的ContentType属性中进行解析和设置。 Here is a complete example of the code; 这是代码的完整示例;

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();
}

The responseMsg property returned by the request as the response can be parsed as a string and otherwise converted to and validated as xml using an expression such as 请求返回的responseMsg属性作为响应可以解析为字符串,否则使用诸如表达式之类的表达式转换为xml并验证为xml

XDocument xdoc = XDocument.Parse(responseMsg);
string xmlAsString = xdoc.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM