用.NET 4.5编写HttpClient

编程入门 行业动态 更新时间:2024-10-26 10:31:53
本文介绍了用.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 fogbugz 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

本文发布于:2023-11-13 01:12:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582997.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!