用.NET 4.5编写HttpClient [英] Encoding with HttpClient in .NET 4.5

查看:149
本文介绍了用.NET 4.5编写HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 fogbugz XML API。此API始终提供数据为UTF-8。



当使用 WebClient 类提出请求时,我可以设置编码。例如:

  var result = new WebClient(); 
result.Encoding = Encoding.UTF8;

但是, HttpClient class? / p>

  HttpClient client = new HttpClient(); 

我应该使用:

  client.GetByteArrayAsync(URL); 

...然后将字节从编码(UTF-8)转换为字符串? / p>

还是有一种直接获取内容作为UTF-8字符串的方法?

 code> using(var client = Connector.GetHttpClient())
{
var byteData = await client.GetByteArrayAsync(url);
data = Encoding.UTF8.GetString(byteData);
}

最后,这是XML响应的摘录:

 <?xml version =1.0encoding =UTF-8?> 
< response>


解决方案

你应该可以使用 - 我希望编码由HTTP响应中的标题确定。如果服务器没有指定编码,那么您应该可以要求修复它。



或者,如果您正在获取XML数据,只需将其作为一个字节数组并直接解析二进制数据 - XML声明应该指定非UTF-8 / UTF-16数据的编码,所以我认为实际上这样做的错误的空间很小。


I'm consuming some data using the XML API. This API always offers data as UTF-8.

When using the WebClient class for making a request I am able to set the encoding. For example:

var result = new WebClient(); 
result.Encoding = Encoding.UTF8;

But what about the HttpClient class?

HttpClient client = new HttpClient();

Should I use:

client.GetByteArrayAsync(url);

...and then convert the bytes from the encoding (UTF-8) to a string?

Or is there a way to directly get the content as a UTF-8 string?

using (var client = Connector.GetHttpClient())
{
    var byteData = await client.GetByteArrayAsync(url);
    data = Encoding.UTF8.GetString(byteData);
}

Finally, here is an excerpt from the XML response:

<?xml version="1.0" encoding="UTF-8"?>
<response>

解决方案

You should be able to use GetStringAsync - I'd expect the encoding to be determined by the headers in the HTTP response. If the server doesn't specify the encoding, then you should potentially ask for that to be fixed.

Alternatively, if you're fetching XML data, just fetch it as a byte array and parse that binary directly - the XML declaration should specify the encoding for non-UTF-8/UTF-16 data anyway, so I'd argue that actually there's less room for error this way.

这篇关于用.NET 4.5编写HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆