【问题标题】:Reading ajax response from Youtube in C#用 C# 从 Youtube 读取 ajax 响应
【发布时间】:2013-08-18 20:43:20
【问题描述】:

我正在尝试在 Youtube 上发表评论并获得 xml 响应(这样我可以获得评论 ID,或者如果我需要输入验证码或其他内容),但我只能发表评论。出于某种原因,我无法使用response.GetResponseStream() 读取 xml 响应。当我尝试将响应输出到控制台时,我什么也得不到。而且,我已经嗅探了我的程序使用 Wireshark 发送和接收的请求和响应,我可以看到 xml 在响应中。

这是我用来读取响应的代码:

using (HttpWebResponse response = MakeRequest(request, cookies, post))
{
    using (var reader = new System.IO.StreamReader(response.GetResponseStream(), UTF8Encoding.UTF8))
    {
        string xml = reader.ReadToEnd();
        Console.WriteLine(xml);
    }
}

和 MakeRequest 函数

private static HttpWebResponse MakeRequest(HttpWebRequest request, CookieContainer SessionCookieContainer, Dictionary<string, string> parameters = null)
{
    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5Accept: */*";
    request.Accept = "text/html,text/xml,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    request.CookieContainer = SessionCookieContainer;
    request.AllowAutoRedirect = false;
    request.KeepAlive = true;

    if (proxy != "") request.Proxy = myproxy;

    if (parameters != null) request.Method = "POST";

    request.ContentType = "application/x-www-form-urlencoded";
    string postData = string.Empty;

    if (parameters != null)
    {
        postData = getPostData(parameters);


        byte[] postBuffer = UTF8Encoding.UTF8.GetBytes(postData);
        using (Stream postStream = request.GetRequestStream())
        {
            postStream.Write(postBuffer, 0, postBuffer.Length);
        }
    }

    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    SessionCookieContainer.Add(response.Cookies);

    while (response.StatusCode == HttpStatusCode.Found)
    {
        response.Close();
        request = GetNewRequest(response.Headers["Location"], SessionCookieContainer);
        response = (HttpWebResponse)request.GetResponse();
        SessionCookieContainer.Add(response.Cookies);
    }

    return response;
}

关于为什么这不起作用以及如何解决此问题的任何想法?

【问题讨论】:

  • 请定义“不工作”。看不懂是什么意思?会发生什么?
  • 我得到一个空白回复。没有任何东西被打印到控制台。
  • 所以你说“而且,我已经嗅探了我的程序使用 Wireshark 发送和接收的请求和响应,我可以看到 xml 在响应中。”意味着您的请求确实返回了结果,但没有返回代码?

标签: c# xml ajax youtube httpwebrequest


【解决方案1】:

我认为切换到 HttpClient 会解决问题。

【讨论】:

    猜你喜欢
    • 2011-12-30
    • 2010-11-05
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多