I'm facing a problem when using HttpClient. The call works right and I get an answer but I can't get the content properly.
The function I wrote looks like this:
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;
}
The response string I get is similar to this one:
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>
This string includes headers for some reason, so when I try to deserialize it I get an error.
How can I remove this headers in the response string?
Your server returns headers in the response body. Would be good to fix this on a server side, if it's not possible you should extract body from the response:
var xml = res.Substring(res.IndexOf("<?xml", StringComparison.Ordinal));