In some cases, we often need to simulate browser operations, such as simulated voting, simulated clicks, or Web game plug-ins. The encapsulated WebClient in C # can implement Http Post and Get in some scenarios where the requirements are not counted. For details, see the code:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Net;
Namespace TestCNM
{
Public class WebClientExt
{
Public string Get (string Url, string Referer, Encoding Encoder, ref string CookieStr)
{
String result = "";
WebClient myClient = new WebClient ();
MyClient. Headers. Add ("Accept :*/*");
MyClient. headers. add ("User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0 ;. NET4.0E ;. NET4.0C; InfoPath.2 ;. net clr 2.0.50727 ;. net clr 3.0.04506.648 ;. net clr 3.5.21022 ;. net clr 3.0.20.6.2152 ;. net clr 3.5.30729; SE 2.X MetaSr 1.0 )");
MyClient. Headers. Add ("Accept-Language: zh-cn ");
MyClient. Headers. Add ("Content-Type: multipart/form-data ");
MyClient. Headers. Add ("Accept-Encoding: gzip, deflate ");
MyClient. Headers. Add ("Cache-Control: no-cache ");
If (CookieStr! = "")
{
MyClient. Headers. Add (CookieStr );
}
MyClient. Encoding = Encoder;
Result = myClient. DownloadString (Url );
If (CookieStr = "")
{
CookieStr = myClient. ResponseHeaders ["Set-Cookie"]. ToString ();
CookieStr = GetCookie (CookieStr );
}
Return result;
}
Public string Post (string Url, string Referer, Encoding Encoder, ref string CookieStr, string Data)
{
String result = "";
WebClient myClient = new WebClient ();
MyClient. Headers. Add ("Accept :*/*");
MyClient. headers. add ("User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0 ;. NET4.0E ;. NET4.0C; InfoPath.2 ;. net clr 2.0.50727 ;. net clr 3.0.04506.648 ;. net clr 3.5.21022 ;. net clr 3.0.20.6.2152 ;. net clr 3.5.30729; SE 2.X MetaSr 1.0 )");
MyClient. Headers. Add ("Accept-Language: zh-cn ");
MyClient. Headers. Add ("Content-Type: multipart/form-data ");
MyClient. Headers. Add ("Accept-Encoding: gzip, deflate ");
MyClient. Headers. Add ("Cache-Control: no-cache ");
If (CookieStr! = "")
{
MyClient. Headers. Add (CookieStr );
}
MyClient. Encoding = Encoder;
Result = myClient. UploadString (Url, Data );
If (CookieStr = "")
{
CookieStr = myClient. ResponseHeaders ["Set-Cookie"]. ToString ();
CookieStr = GetCookie (CookieStr );
}
Return result;
}
Private string GetCookie (string CookieStr)
{
String result = "";
String [] myArray = CookieStr. Split (',');
If (myArray. Count ()> 0)
{
Result = "Cookie :";
Foreach (var str in myArray)
{
String [] CookieArray = str. Split (';');
Result + = CookieArray [0]. Trim ();
Result + = ";";
}
Result = result. Substring (0, result. Length-2 );
}
Return result;
}
}
}
Author: aofengdaxia