HttpClient coding in .NET 4.5

I consume some data using XML API. This API always offers data like UTF-8.

When using the WebClient class to execute a request, I can set the encoding. For instance:

 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 contents 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> 
+6
source share
2 answers

You can use GetStringAsync - I expect the encoding will be determined by the headers in the HTTP response. If the server does not specify an encoding, you should ask for it to be fixed.

Alternatively, if you are extracting XML data, just select it as an array of bytes and parse this binary directly - the XML declaration should indicate the encoding for data other than UTF-8 / UTF-16, so I would argue that on in fact, there is less room for errors.

+9
source

If I understood correctly, you do not need a string, you need XML.

So, if your data is not too large, read an array of bytes with

 byte[] bytes = await client.GetByteArrayAsync(url); 

then create a memory stream from this array, and then read the XML from this stream, for example:

 XElement element = XElement.Load(new MemoryStream(bytes), LoadOptions.None); 

If you are using a different XML API, you can use

 XmlReader reader = XmlReader.Create(new MemoryStream(bytes)); 
+3
source

Source: https://habr.com/ru/post/917997/


All Articles