In actual programming, you may need to read the information of a specific webpage. However, many websites require users to log on to obtain the relevant page content. This requires programmers to temporarily store the current cookie, in C #, you can use the CookieContainer object to save the Cookie information after logon. In this way, you can append the Cookie information each time you send data.
# Region synchronously sends data through POST
/// <Summary>
/// Send data through POST
/// </Summary>
/// <Param name = "Url"> url </param>
/// <Param name = "postDataStr"> Post Data </param>
/// <Param name = "cookie"> Cookie container </param>
/// <Returns> </returns>
Public string SendDataByPost (string Url, string postDataStr, ref CookieContainer cookie)
{
HttpWebRequest request = (HttpWebRequest) WebRequest. Create (Url );
If (cookie. Count = 0)
{
Request. CookieContainer = new CookieContainer ();
Cookie = request. CookieContainer;
}
Else
{
Request. CookieContainer = cookie;
}
Request. Method = "POST ";
Request. ContentType = "application/x-www-form-urlencoded ";
Request. ContentLength = postDataStr. Length;
Stream myRequestStream = request. GetRequestStream ();
StreamWriter myStreamWriter = new StreamWriter (myRequestStream, Encoding. GetEncoding ("gb2312 "));
MyStreamWriter. Write (postDataStr );
MyStreamWriter. Close ();
HttpWebResponse response = (HttpWebResponse) request. GetResponse ();
Stream myResponseStream = response. GetResponseStream ();
StreamReader myStreamReader = new StreamReader (myResponseStream, Encoding. GetEncoding ("UTF-8 "));
String retString = myStreamReader. ReadToEnd ();
MyStreamReader. Close ();
MyResponseStream. Close ();
Return retString;
}
# Endregion
# Region synchronously sends data through GET
/// <Summary>
/// Send data through GET
/// </Summary>
/// <Param name = "Url"> url </param>
/// <Param name = "postDataStr"> GET data </param>
/// <Param name = "cookie"> GET container </param>
/// <Returns> </returns>
Public string SendDataByGET (string Url, string postDataStr, ref CookieContainer cookie)
{
HttpWebRequest request = (HttpWebRequest) WebRequest. Create (Url + (postDataStr = ""? "":"? ") + PostDataStr );
If (cookie. Count = 0)
{
Request. CookieContainer = new CookieContainer ();
Cookie = request. CookieContainer;
}
Else
{
Request. CookieContainer = cookie;
}
Request. Method = "GET ";
Request. ContentType = "text/html; charsets = UTF-8 ";
HttpWebResponse response = (HttpWebResponse) request. GetResponse ();
Stream myResponseStream = response. GetResponseStream ();
StreamReader myStreamReader = new StreamReader (myResponseStream, Encoding. GetEncoding ("UTF-8 "));
String retstring = mystreamreader. readtoend ();
Mystreamreader. Close ();
Myresponsestream. Close ();
Return retstring;
}
# Endregion