我创建了一个具有 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
对象并将每个 HttpWebRequest
的 CookieContainer
属性设置为 CookieContainer
实例。
关于c# - Web 请求和响应的 cookies 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2492839/