使用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>
此字符串出于某些原因包含标头,因此当我尝试反序列化它时,会出现错误。
如何删除响应字符串中的标头?
答案 0 :(得分:1)
您的服务器在响应正文中返回标头。最好在服务器端修复此问题,如果不可能的话,您应该从响应中提取正文:
var xml = res.Substring(res.IndexOf("<?xml", StringComparison.Ordinal));
答案 1 :(得分:0)
您可以尝试以下方法:
using (var receiveStream = response.GetResponseStream())
{
using (var readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
Console.WriteLine (readStream.ReadToEnd ());
}
}