Web响应在控制台中返回随机符号,但在保存到文件

时间:2018-02-25 09:52:05

标签: c# httpwebrequest

我正在尝试向api发出Web请求,该api返回包含所有产品的JSON文件。我的问题是,当我收到回复时,它包含随机的'?'像这样:

"name":"Ri?pple? L/S ?Te?e","id":303071

但是,当我将回复保存到文本文档或将其设置为剪贴板并将其粘贴到'?'消失了。只有项目名称才会出现此问题。

这是我的代码

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com/mobile_stock.json");
request.Method = "GET";
request.KeepAlive = true;
request.AutomaticDecompression = DecompressionMethods.Deflate;
request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14A403 Safari/602.1";


HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();
StreamReader _str2 = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string html = _str2.ReadToEnd();

Console.WriteLine(html); //Writes response to console. (Contains '?')

string destPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mobile.txt");
File.WriteAllText(destPath, html, Encoding.UTF8); //Saves response to file (Doesn't containt '?')

我已经向某人询问了一个解决方案,他说如果我将其编码为utf-8,它应该可以正常工作,我在代码中看到的但是在编写控制台时问题仍然存在。此外,如果我尝试做string.replace'?'仍然存在。

1 个答案:

答案 0 :(得分:0)

试试这个:

Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine(html);