使用HTTP客户端编码在.NET 4.5 [英] Encoding with HTTP Client in .net 4.5

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

问题描述

我消耗的FogBugz XML API的一些数据。这个API总是提供UTF-8的数据。

在使用WebClient类进行的GetRequest我能够设置编码。 例如:

  VAR的结果=新的Web客户端();
result.Encoding = Encoding.UTF8;
 

但对于HttpClient的?

  HttpClient的客户端=新的HttpClient();
 

我应该使用:

  client.GetByteArrayAsync(URL);
 

,然后从编码(UTF8),以字符串转换字节?

是有办法获得直接写给utf8的字符串?

 使用(VAR的客户= Connector.GetHttpClient())
{
    VAR byteData =等待client.GetByteArrayAsync(URL);
    数据= Encoding.UTF8.GetString(byteData);
}
 

添加 从XML响应示例

 < XML版本=1.0编码=UTF-8&GT?;
<响应>
 

解决方案

您应该可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.getstringasync%28v=vs.110%29"><$c$c>GetStringAsync - 我期望的编码由HTTP响应标题来确定。如果服务器没有指定编码,那么你应该可能问的是固定的。

另外,如果你在获取XML数据,就直接把它拿来作为一个字节数组,并解析二进制 - XML声明应指定非UTF-8 / UTF-16数据的编码,无论如何,所以我认为实际上有错误的余地更小这样的。

I'm consuming some data of the fogbugz XML Api. This api always offers UTF-8 Data.

When using the WebClient Class for GetRequest I was able to set the encoding. For example:

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

But what about the httpclient ?

HttpClient client = new HttpClient();

Should I use:

client.GetByteArrayAsync(url);

and then convert the bytes from the encoding (UTF8) to string?

of is there a way to get diretly the utf8 string?

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

Added Sample 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.

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

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