6

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

0

3 Answers 3

6

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;
}  
Sign up to request clarification or add additional context in comments.

1 Comment

It's so weird that it won't work if you have BaseAddress already set up and you're trying to do that via GetAsync("/") you need to specify the URL in GetAsync, lol
2

Figured it out!

I should have added a Accept header and its type should be "application/xml".

The working version:

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.Accept.ToString(), "application/xml");
  returnedXml = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
}   

Comments

0

Refactored version of the existing answers here,

using var client = new HttpClient();
client
    .DefaultRequestHeaders
    .Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Text.Xml));
client.Timeout = TimeSpan.FromSeconds(500);
var response = await client.GetAsync("Put your URL right here!");
if (response.IsSuccessStatusCode)
{
    var responseContent = await response.Content.ReadAsStringAsync();
    if (string.IsNullOrWhiteSpace(responseContent) == false)
// etc etc etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.