HttpWebResponse正文无法读取

时间:2015-12-17 23:24:57

标签: c# http web httpwebrequest httpwebresponse

我创建了一个与Picarto.tv集成的c#应用程序。

问题出在登录阶段,程序必须将具有登录详细信息的WebRequest发送到picarto登录服务器并接收响应。我成功发送了请求,但响应完全无法读取,并且长度与常规登录过程中服务器发回的内容不一致(如使用Chrome和Firefox开发工具发现的那样)。

以下是相关函数的代码:

public void login(String username, String password)
    {

        HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create("https://picarto.tv/process/login");

        //Set request headers. 
        loginRequest.Method = "POST";
        loginRequest.CookieContainer = cookieJar = new CookieContainer();
        loginRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
        loginRequest.Referer = "https://picarto.tv/";
        loginRequest.Credentials = new NetworkCredential(username, password);
        loginRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36";
        loginRequest.Accept = "application/json, text/html, */*; q=0.01";
        loginRequest.Headers["accept-encoding"] = "gzip, deflate";

        //If you comment the line below, you the resulting report string becomes 25 bytes long but is displayed only as "?"
        //Otherwise, the report value stays empty.
        loginRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; //???

        loginRequest.Headers["accept-language"] = "gen-US,en;q=0.8";

        //Set request body
        byte[] request = Encoding.UTF8.GetBytes("username="+ username + "&password="+ password + "&stayLogged=false");
        loginRequest.ContentLength = request.Length;

        Stream requestStream = loginRequest.GetRequestStream();
        requestStream.Write(request, 0, request.Length);
        requestStream.Close();

        //Get response
        HttpWebResponse loginResponse = (HttpWebResponse) loginRequest.GetResponse();
        Stream responseStream = loginResponse.GetResponseStream();

        Console.WriteLine("Content length: " + loginResponse.ContentLength);  //Always -1.

        //Read response body
        StreamReader reader = new StreamReader(responseStream);
        string report = reader.ReadToEnd(); //The report is always either empty or unreadable.

        //Display response body
        Console.WriteLine("length: " + report.Length+ " report: " +report);
        reader.Close();
    }

我使用过Fiddler并确定无论配置如何,响应都有一个36-40字节的主体,但Fiddler本身无法解码消息,而是在提示解码时丢弃它。

我的第一个想法是消息是编码的,但是由于某些内部原因,C#无法对其进行解码,但是我的同事已经将生成的主体提供给gzip解码器,并确定响应主体不是有效的gzip流。

我试图尽可能接近地模仿登录请求,但显然缺少某些东西。

我知道代码很乱,并且缺少许多重要的结构(比如异常管理块)。为了简洁的演示和方便,我把它们留给了目的。

修改1:根据建议(在目前似乎已删除的帖子中),我尝试将loginRequest.AutomaticDecompression值更改为DecompressionMethods.None并评论accept-encoding标题。情况没有改变,除了Fiddler现在只记录在响应体中发回的5个字节(并且仍然无法对其进行解码)。

0 个答案:

没有答案