首页 > 解决方案 > 从 HttpClient 响应中删除标头

问题描述

使用 HttpClient 时遇到问题。通话正常,我得到了答案,但我无法正确获取内容。

我写的函数是这样的:

    public async Task<string> MakePostRequestAsync(string url, string data, CancellationToken cancel)
    {
        String res = String.Empty;

        using (HttpClient httpClient = new HttpClient())
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            HttpContent content = new StringContent(data, Encoding.UTF8, "application/xml");
            httpClient.DefaultRequestHeaders.Authorization = getHeaders();
            httpClient.DefaultRequestHeaders.Add("Accept", "application/xml");
            httpClient.DefaultRequestHeaders.Add("User-Agent", "C#-AppNSP");
            httpClient.DefaultRequestHeaders.ExpectContinue = false;

            HttpResponseMessage response = await httpClient.PostAsync(url, content, cancel);
            response.EnsureSuccessStatusCode(); // Lanza excepción si no hay éxito

            res = await response.Content.ReadAsStringAsync();
            if (String.IsNullOrEmpty(res))
            {
                throw new Exception("Error: " + response.StatusCode);
            }
        }

        return res;
    }

我得到的响应字符串类似于这个:

HTTP/1.1 0 nullContent-Type: application/xml;charset=UTF-8
Content-Length: 1263
Date: Tue, 02 Jul 2019 07:48:07 GMT
Connection: close

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SeguimientoEnviosFechasResponse xsi:noNamespaceSchemaLocation="SeguimientoEnviosFechasResponse.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Error>0</Error>
    <MensajeError></MensajeError>
    <SeguimientoEnvioFecha>
        <!-- more XML here -->
    </SeguimientoEnvioFecha>
</SeguimientoEnviosFechasResponse>

由于某种原因,此字符串包含标头,因此当我尝试反序列化它时出现错误。

如何在响应字符串中删除此标头?

标签: c#.netxml-parsingdotnet-httpclientwebservice-client

解决方案


您的服务器在响应正文中返回标头。在服务器端解决这个问题会很好,如果不可能,你应该从响应中提取正文:

        var xml = res.Substring(res.IndexOf("<?xml", StringComparison.Ordinal));

推荐阅读