C#HttpRequest附加Cookie以请求

时间:2022-10-14 21:01:18

I want to send a cookie pulled from Google Chromes network F12 tab to preproduce hitting the UI in an HTTP Request instead. However, I need to send the cookie that goes with the request. I can't seem to attach the cookie string to the request.

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

Capture from Google Chrome (f12) http://imgur.com/8wEaSSC.png

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

I need to attach that cookie to the request when I send it out.

我发送时,我需要将该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 个解决方案

#1


Add the lines:

添加行:

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

Don`t forget replace "your domain here" to domain of target request Uri

不要忘记将“您的域名”替换为目标请求Uri的域名

#1


Add the lines:

添加行:

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

Don`t forget replace "your domain here" to domain of target request Uri

不要忘记将“您的域名”替换为目标请求Uri的域名