c# - Web 请求和响应的 cookies 处理

标签 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;
}

最佳答案

您需要创建一个 CookieContainer对象并将每个 HttpWebRequestCookieContainer 属性设置为 CookieContainer 实例。

关于c# - Web 请求和响应的 cookies 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2492839/

相关文章:

c# - 持久化 bool 逻辑

c# - 从命名空间获取所有类并处理它们的属性

C# 运算符和可读性

c# - 如何使用 Linq 选择列名

c# - 如何在自定义服务器控件 asp 中使用 .resx 和 .resource 文件?

c# - 为什么我不能在 MVC Controller 中使用 System.IO.File 方法?

c# - 在 Visual Studio 2013 中运行单元测试时运行其他项目

c# - 为什么我的 ActionBlock 在我没有设置的情况下就处于已完成状态?

c# - 使用 SqlCommand.ExecuteScalar() 从序列中选择在高磁盘使用率时返回 NULL

c# - 从对象初始值设定项访问属性