处理webrequest和响应的cookie

时间:2010-03-22 14:12:47

标签: c#

我创建了一个具有函数mainpost的应用程序。创建它是为了在https站点上发布数据。在这里,我想在这个功能中处理cookie。我该怎么做这个任务?

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 StreamReader(response.GetResponseStream()).ReadToEnd());
    Console.WriteLine(response.StatusCode);

    return str;
}

2 个答案:

答案 0 :(得分:3)

您需要制作一个CookieContainer对象,并将每个CookieContainer的{​​{1}}属性设置为HttpWebRequest个实例。

答案 1 :(得分:0)

您需要在请求之间设置CookieContainer Property

如果您维护相同的cookie容器,则将在以后的请求中重新发送cookie。