简体   繁体   中英

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 .

Error -> Cannot convert string to 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. The MediaTypeHeaderValue is parsed and set in the ContentType property of the content Headers. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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