c# WebClient with fidler2 (单独的结果)

本文关键字:单独 结果 closed and with WebClient fidler2 open | 更新日期: 2023-09-27 18:03:06

所以我只是想使用WebClient创建一个基本的堆栈溢出客户端。当我按原样运行程序时,即使我休眠并等待,也会得到一个空字符串结果。然而,当我打开Fiddler2程序工作…我要做的就是打开提琴手…下面是相关代码。

public partial class MainWindow : Window
{
    public  ObservableCollection<question>  questions { get; set; }
    public MainWindow() 
    {
        questions = new ObservableCollection<question>();
        this.DataContext = this;
        InitializeComponent();
    }
    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        MessageBox.Show(e.Result); //Right here is the difference. When 
        <BREAK POINT HERE OR IT BREAKS>
        string data = data = e.Result.Substring(e.Result.IndexOf("class='"question-summary narrow'"") + 31);
        string content = data.Substring(0, data.IndexOf("class='"question-summary narrow'""));
        string v, a, t, b, tgs, link;
        questions.Add(new question
            {
                //votes = v,
                //answers = a,
                //title = t.ToUpper(),
                //body = b,
                ////tags = tgs
                //href = link
             });
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        WebClient wc = new WebClient();
        wc.DownloadStringAsync(new Uri(@"http://api.stackoverflow.com/1.1/questions"));
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
    }
}
public class question
{
    public string votes { get; set; }
    public string answers { get; set; }
    public string title { get; set; }
    public string body { get; set; }
    public string tags { get; set; }
    public string href { get; set; }
}

同样值得注意的是fidler的结果当我在浏览器中加载http://api.stackoverflow.com/1.1/questions时fiddler显示

http://api.stackoverflow.com/1.1/questions200 OK (application/json)

http://api.stackoverflow.com/favicon.ico503 Service Unavailable (text/html)

当我在程序中加载它时只有这个显示

http://api.stackoverflow.com/1.1/questions200 OK (application/json)

c# WebClient with fidler2 <open and closed>(单独的结果)

看起来问题出在API本身。即使你没有告诉它你接受GZipped内容,它还是GZipped它,显然Fiddler处理和解压缩它为你。在你的应用中,你必须通过解压缩内容来解决这个问题。下面是一个简单的例子:

var wc = new WebClient();
var bytes = wc.DownloadData(new Uri(@"http://api.stackoverflow.com/1.1/questions"));
string responseText;
using (var outputStream = new MemoryStream())
{
    using (var memoryStream = new MemoryStream(bytes))
    {
        using (var gzip = new GZipStream(memoryStream, CompressionMode.Decompress))
        {
            byte[] buffer = new byte[1024];
            int numBytes;
            while ((numBytes = gzip.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 0, numBytes);
            }
        }
        responseText = Encoding.UTF8.GetString(outputStream.ToArray());
    }
}
Console.WriteLine(responseText);

无论它是否总是gzip,谁知道-你可以检查内容编码HTTP头,看看它是否是gzip,如果是,然后运行这段代码,如果不是,然后你可以直接转换成文本的字节