Xamarin: エラー"System.NotSupportedException: Encoding 932 data could not be found. Make sure you have correct international codeset assembly installed and enabled."

概要

System.Net.Http.HttpContent.ReadAsStringAsync()メソッドを使用した際に以下のエラーが発生した場合の対応方法。

System.NotSupportedException: Encoding 932 data could not be found. Make sure you have correct international codeset assembly installed and enabled.

エラー

以下のコードを実行した際にこのSystem.NotSupportedExceptionが発生する場合がある。

HttpResponseMessage response = await client.GetAsync("https://www.google.com");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("responseBody=" + responseBody);

エラーのスタックトレース

2020-04-29 22:26:56.159 XamarinHttp.iOS[2512:843471] System.NotSupportedException: Encoding 932 data could not be found. Make sure you have correct international codeset assembly installed and enabled.
  at System.Text.Encoding.GetEncoding (System.Int32 codepage) [0x0021d] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/text/encoding.cs:553 
  at System.Text.Encoding.GetEncoding (System.String name) [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/text/encoding.cs:695 
  at System.Net.Http.HttpContent.ReadBufferAsString (System.ArraySegment`1[T] buffer, System.Net.Http.Headers.HttpContentHeaders headers) [0x00019] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpContent.cs:205 
  at System.Net.Http.HttpContent.ReadBufferedContentAsString () [0x0002f] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpContent.cs:186 
  at System.Net.Http.HttpContent+<>c.<ReadAsStringAsync>b__36_0 (System.Net.Http.HttpContent s) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpContent.cs:168 
  at System.Net.Http.HttpContent.WaitAndReturnAsync[TState,TResult] (System.Threading.Tasks.Task waitTask, TState state, System.Func`2[T,TResult] returnFunc) [0x0006b] in <643a547f99044b5596a1ffebd1166379>:0 
  at XamarinHttp.MainPage.HttpRequestAsync () [0x000bd] in /Users/shindo/Projects/XamarinHttp/XamarinHttp/MainPage.xaml.cs:33 
  at XamarinHttp.MainPage.OnButtonClicked (System.Object sender, System.EventArgs eventArgs) [0x00023] in /Users/shindo/Projects/XamarinHttp/XamarinHttp/MainPage.xaml.cs:55 

解決策

以下のようにReadAsByteArrayAsync()メソッドを使用してbyte[]でデータを取得してから、エンコードを指定して文字列に変換する。

HttpResponseMessage response = await client.GetAsync("https://www.google.com");
response.EnsureSuccessStatusCode();
byte[] responseBody = await response.Content.ReadAsByteArrayAsync();
Console.WriteLine("responseBody=" + Encoding.UTF8.GetString(responseBody));