开发者

cookies handling on webrequest and response

开发者 https://www.devze.com 2022-12-24 18:47 出处:网络
I have created a application that has a function mainpost. It is created to post data on a https sites. Here I want to handle cookies in this function. How can I do this task?

I have created a application that has a function mainpost. It is created to post data on a https sites. Here I want to handle cookies in this function. How can I do this task?

public string Mainpost(string website, string content)
{
    // this is what we are sending
    string post_data = content;

    // this is where we will send it
    string uri = website;

    // create a request
    HttpWebRequest request = (HttpWebRequest)
    WebRequest.Create(uri); request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;
    request.Method = "POST";

    // turn our request string into a byte stream
    byte[] postBytes = Encoding.ASCII.GetBytes(post_data);

    // this is important - make sure you specify type this way
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = postBytes.Length;
    Stream requestStream = request.GetRequestStream();

    // now send it
    requestStream.Write(postBytes, 0, postBytes.Length);
    requestStream.Close();

    // grab te response and print it out to the console along with the status
    // code
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string str = (new Strea开发者_JAVA技巧mReader(response.GetResponseStream()).ReadToEnd());
    Console.WriteLine(response.StatusCode);

    return str;
}


You need to make a CookieContainer object and set the CookieContainer property of each HttpWebRequest to the CookieContainer instance.


You need to set the CookieContainer Property between requests.

If you maintain the same cookie container the cookies will be resent with future requests.

0

精彩评论

暂无评论...
验证码 换一张
取 消