C#HttpRequest附加Cookie以请求

时间:2015-05-07 13:47:34

标签: c# cookies httprequest

我想发送从Google Chromes网络F12标签中提取的Cookie,以便在HTTP请求中预先生成用户界面。但是,我需要发送与请求一起发送的cookie。我似乎无法将cookie字符串附加到请求中。

从谷歌浏览器捕获(f12) http://imgur.com/8wEaSSC.png

当我发送请求时,我需要将该cookie附加到请求中。

        string cookie = "JSESSIONID_loginLite_remote=LJyKVLHGLZrpTq3npBWh8CJyqTND32HpscL48ndnSp0hj2g6yhcK!.....";
        string info = "RemoteObjectTimestamp=1430842283795&RemoteObjectRequest=%7B%22destination%22%...";

        char[] arr      = info.ToCharArray(); 
        byte[] data     = System.Text.Encoding.ASCII.GetBytes(arr);

        HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
        myHttpWebRequest.Method         = "POST";
        myHttpWebRequest.ContentType    = "application/x-www-form-urlencoded;charset=UTF-8";
        myHttpWebRequest.ContentLength  = data.Length;

        //Data to write is not empty
        if (data.Length > 0)
        {
            Stream requestStream = myHttpWebRequest.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
        }

        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

        Stream responseStream = myHttpWebResponse.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(responseStream, System.Text.Encoding.Default);
        string pageContent = myStreamReader.ReadToEnd();

        myStreamReader.Close();
        responseStream.Close();
        myHttpWebResponse.Close();

        Console.WriteLine(pageContent);

1 个答案:

答案 0 :(得分:0)

添加以下行:

myHttpWebRequest.CookieContainer = new CookieContainer();  
myHttpWebRequest.CookieContainer.SetCookies(new Uri("your domain here"), cookie);

不要忘记在这里替换你的域名"到目标请求Uri的域