WebClient.DownloadString结果与浏览器结果2不匹配

时间:2015-12-21 22:40:24

标签: c# encoding webclient downloadstring

以下代码:

WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
string Url = "http://www.tsetmc.com/tsev2/data/instinfodata.aspx?i=59266699437480384&c=64";
return wc.DownloadString(Url);

代码返回:

�Q�T�MP�J�A|�^D����~���C�"�����l� ��;I&3=j=�iG�H9Ȓ�J�^� �j��T�Q=HH�'Qm�������1�hF�4�*�������{�x�\o?

当我在任何网络浏览器中访问该网址时,我得到:

12:29:45,A ,3540,3567,3600,3621,3690,3515,140,238204,849582597,1,20140914,122945;;1@2825@3523@3583@1700@1,1@2000@3522@3600@8700@2,1@500@3511@3640@2500@1,;19774,99736,1

有没有办法得到正确的字符串?

另外,我使用这个在线解码器,但我得不到正确答案: Universal Online Decoder

3 个答案:

答案 0 :(得分:3)

这不是编码问题,我认为它与压缩有关,在这种情况下是gzip。阅读Uncompressing gzip response from WebClient。 这应该可以解决你的问题。

答案 1 :(得分:2)

public class WC : WebClient
{
    protected override WebRequest GetWebRequest(Uri url)
    {
        var request = base.GetWebRequest(url) as HttpWebRequest;
        request.AutomaticDecompression = DecompressionMethods.GZip;

        return request;
    }
}

用法:

var url = "http://www.tsetmc.com/tsev2/data/instinfodata.aspx?i=59266699437480384&c=64";
var wc = new WC();
wc.Encoding = Encoding.UTF8;
var result = wc.DownloadString(url);

答案 2 :(得分:2)

在Linqpad中,您可以运行以下代码,即Webclient的变体。从图片中可以看出,由于浏览器自动处理的Gzip压缩。  enter image description here

async void Main()
{
    using (var handler = new HttpClientHandler())
    {
        handler.AutomaticDecompression = DecompressionMethods.GZip;
        using (HttpClient client = new HttpClient(handler))
        {
            var result = await client.GetStringAsync("http://www.tsetmc.com/tsev2/data/instinfodata.aspx?i=59266699437480384&c=64");
            result.Dump();
        }
    }
}