Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

c# - Encoding with HttpClient in .NET 4.5

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...