2

所以我只是想用WebClient. 当我按原样运行程序时,即使我睡觉并等待,我也会得到一个空字符串结果。但是,当我打开 Fiddler2 时,程序可以工作......我所要做的就是打开 Fiddler......这是相关代码。

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; }
}

另外值得注意的是提琴手结果当我在浏览器中加载http://api.stackoverflow.com/1.1/questions时提琴手显示

获取http://api.stackoverflow.com/1.1/questions 200 确定(应用程序/json)

获取http://api.stackoverflow.com/favicon.ico 503 服务不可用(文本/html)

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

获取http://api.stackoverflow.com/1.1/questions 200 确定(应用程序/json)

4

1 回答 1

4

看起来问题出在 API 本身。即使您没有告诉它您接受 GZipped 内容,它仍然是 GZipping 它,显然 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);

不管它是否总是 GZipped,谁知道——你可以检查 Content-Encoding HTTP 标头以查看它是否是gzip,如果是,则运行此代码,如果不是,则可以将字节直接转换为文本。

于 2013-03-08T20:42:06.103 回答