从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>

此字符串出于某种原因包括标题,因此当我尝试进行挑选时,我会遇到错误。

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

您的服务器返回响应主体中的标题。将其修复在服务器端将是一件好事,如果不可能,您应该从响应中提取身体:

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

您可以尝试以下方法:

using (var receiveStream = response.GetResponseStream()) 
{
  using (var readStream = new StreamReader(receiveStream, Encoding.UTF8)) 
  {
    Console.WriteLine (readStream.ReadToEnd ());
  }
}

相关内容

  • 没有找到相关文章

最新更新