Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consuming xml using HttpClient from webapi

I used WebClient to get an Xml object from a restfull service (.net web api) and everything worked great:

using(WebClient client = new WebClient())
{
   client.Encoding = UTF8Encoding.UTF8;
   client.Headers[HttpRequestHeader.ContentType] = "text/xml";
   client.Credentials = // ....;
   xmlResult = webClient.DownloadString(url);
}

....

this code works great. I get an Xml as a string back, everyone's happy.

Now, I changed it so it would work with HttpClient instead and I can't get an Xml returned - always a json as a string.

using(var handler = new HttpClientHandler() {Credentials = new NetworkCredentials})
using(var client = new HttpClient(handler))
{
   var request = new HttpRequestMessage(HttpMethod.Get, url);
   request.Headers.Add(HttpRequestHeader.ContentType.ToString(), "text/xml");
   returnedXml = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
}   

What am I doing wrong? How can I get the Xml I long for?

Thanks

like image 498
Rotem B Avatar asked Jun 29 '15 12:06

Rotem B


1 Answers

Just Try this one ..

using(var handler = new HttpClientHandler() {Credentials = new NetworkCredentials})
using(var client = new HttpClient(handler))
{
      client.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("text/xml"));
   var request = new HttpRequestMessage(HttpMethod.Get, url);
    returnedXml = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
}  
like image 135
Jagadeesh Govindaraj Avatar answered Sep 18 '22 11:09

Jagadeesh Govindaraj