在C#中读取Youtube的ajax响应

时间:2013-08-16 12:28:46

标签: c# xml ajax youtube httpwebrequest

我正在尝试在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;
}

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

1 个答案:

答案 0 :(得分:0)

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