在C#中读取Youtube的ajax响应

时间:2022-01-14 20:16:45

I'm trying to post a comment on Youtube and get the xml response (so I can get the comment ID, or if I need to enter captcha or something), but I'm only able to post the comment. For some reason I am not able to read the xml response by using response.GetResponseStream(). When I try to output the response to the console, I get nothing. And, I've sniffed the requests and response my program sends and receives using Wireshark and I can see that the xml is in the response.

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

Here is the code I'm using to read the response:

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

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

and the MakeRequest function

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

Any ideas on why this isn't working and how to solve this issue?

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

1 个解决方案

#1


0  

I think switching to HttpClient would solve the problem.

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

#1


0  

I think switching to HttpClient would solve the problem.

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