使用webapi中的HttpClient来使用xml

时间:2015-06-29 12:19:31

标签: .net asp.net-web-api dotnet-httpclient

我使用WebClient从restfull服务(.net web api)获取Xml对象,一切运行良好:

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

....

这段代码效果很好。我得到一个Xml作为字符串,每个人都很高兴。

现在,我更改了它以便它可以与HttpClient一起使用而且我无法返回Xml - 总是将json作为字符串。

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;
}   

我做错了什么?我怎样才能获得我想要的Xml?

由于

2 个答案:

答案 0 :(得分:5)

试试这个......

/*
Tells the delegate that the table view is about to draw a cell for a particular row. (optional)
*/
override func tableView(tableView: UITableView,
    willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath)
{
    // Row 2 at Section 2
    if indexPath.row == 1 && indexPath.section == 1 {
        // Hiding separator line for one specific UITableViewCell
        cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)

        // Here we add a line at the bottom of the cell (e.g. here at the second row of the second section).
        let additionalSeparatorThickness = CGFloat(1)
        let additionalSeparator = UIView(frame: CGRectMake(0,
            cell.frame.size.height - additionalSeparatorThickness,
            cell.frame.size.width,
            additionalSeparatorThickness))
        additionalSeparator.backgroundColor = UIColor.redColor()
        cell.addSubview(additionalSeparator)
    }
}

答案 1 :(得分:1)

想出来了!

我应该添加一个Accept标头,其类型应为" application / xml"。

工作版本:

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;
}