和风天气 API 乱码解决方法

最近在使用和风天气 API 时,出现了乱码的 bug。API 返回结果在浏览器上能正常显示,但是程序读出的 JSON 文件是乱码,并且修改字符编码也没有用。后来在官方文档中看到这样一条
默认 Gzip 压缩
于是在读取时需要注意加点东西,读取 JSON 的代码如下(C#)

using System.IO;
using System.IO.Compression;

public static string GetJSON(string url) {
	HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
	HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
	Stream stream = httpResponse.GetResponseStream();
	// 和风天气默认使用 Gzip 压缩,直接用 StreamReader 会乱码
	StreamReader reader = new StreamReader(new GZipStream(stream, CompressionMode.Decompress), Encoding.GetEncoding("utf-8"));
	string result = reader.ReadToEnd();
	stream.Close();
	return result;
}

看到微软官方文档说了,建议你不要将 HttpWebRequest 用于新的开发。而应使用 System.Net.Http.HttpClient 类。 那我们就用 HttpClient 再写个

using System.Net;
using System.Net.Http;

public static string GetJSON(string url) {
    string result = "";
    // 创建 HttpClientHandler,并用 GZip 解压
    HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
    using (HttpClient http = new HttpClient(handler)) {
        HttpResponseMessage response = http.GetAsync(url).Result;
        if (response.IsSuccessStatusCode) {
            result = response.Content.ReadAsStringAsync().Result;
        }
    }
    return result;
}

中间涉及到异步(async)操作的一些问题,我按微软文档里抄的写法会导致程序卡死,我也没太理解原因 我就是无情的 CRUD 机器 ,所以这里提供的是一个 能运行,看起来不错 的方案(参考 StackOverflow: HttpClient GetAsync not working as expected),欢迎大家补充原理和分析。

posted @ 2020-08-27 23:27  BwShen  阅读(190)  评论(0编辑  收藏  举报