c# - 从 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));
推荐阅读
- google-api - 跟踪昵称为 Meets 出勤率
- kotlin - Kotlin 1.5 频道 trySendBlocking() 与 trySend()
- reactjs - “TypeError:无法在反应js中设置未定义的属性'电子邮件'”?
- if-statement - IF WITH ORs 条件未按预期运行 PL/SQL
- python - 在 tkinter 中创建多个帧
- python - 使用 RBG 对图像进行阈值处理
- javascript - 启用和禁用带有复选框的提交按钮
- azure-devops - 通过 Azure DevOps 执行 SPFx 部署时访问被拒绝错误
- powerbi - Power BI(分页报表):覆盖默认错误消息
- android - 手机上的Xamarin程序如果已经卸载重装会出现问题