I am converting code from HttpWebRequest to HttpClient . One of the problems I ran into is getting the encoding from the response header of the content type.
When using HttpWebRequest encoding is displayed in the HttpWebResponse.CharacterSet property, for example,
using (WebResponse response = await this.webRequest.GetResponseAsync()) { string characterSet = ((HttpWebResponse)response).CharacterSet;
You can also access it from the WebResponse.ContentType property or from the content header in HttpWebResponse.Headers .
Using HttpClient , the encoding seems to be missing from the ContentType header.
Here is the code I use for HttpClient :
using (HttpClient httpClient = new HttpClient(httpClientHandler)) { using (HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseContentRead)) { charset = httpResponseMessage.Content.Headers.ContentType.CharSet;
The CharSet property is always null . HttpResponseMessage has a Headers property, but does not contain a content header. HttpResponseMessage.Content also has a Headers property, which appears to contain a content type header, but this header shows "Content-Type: text/html" - it does not have a charset part.
Using the first approach with HttpWebResponse for the same URL, I get the encoding part of the Content-Type header. Did I miss something?
source share