ASP tutorial. NET HTTP Get cookies
Cookies, sometimes in their plural form, are the data (usually encrypted) that some Web sites store on the user's local terminal in order to identify the user and perform session tracking. defined in rfc2109 (deprecated), the latest superseded specification is rfc2965.
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Net;
5 using System.IO;
6 using System.net.cache;
7 using System.Drawing;
8 using System.Text.RegularExpressions;
9 using System.runtime.interops tutorial ervices;
10
One namespace Httpsimulation
12 {
///<summary>
14 Methods of///access to the network
///</summary>
public enum Httprequesttype
17 {
///<summary>
///POST Request
///</summary>
Post,
///<summary>
///GET Request
///</summary>
/Get
26}
///<summary>
28///The method class that gets the cookie.
///</summary>
public class Cookiemanger
31 {
[DllImport ("Wininet.dll", SetLastError = True)]
The public static extern bool InternetGetCookie (string URL, String cookiename, StringBuilder cookiedata, ref int Si Ze);
[DllImport ("kernel32.dll", SetLastError = True)]
private static extern int GetLastError ();
36
Notoginseng public static Cookiecontainer Geturicookiecontainer (URI uri)
38 {
Cookiecontainer cookies = null;
40//Defines the size of the cookie data.
(a) int datasize = 256;
StringBuilder cookiedata = new StringBuilder (datasize);
43
if (!internetgetcookie (uri.tostring (), NULL, Cookiedata, ref datasize))
45 {
+ int errcode = GetLastError ();
if (DataSize < 0)
return null; Be sure to have enough space to hold the cookie data.
Cookiedata = new StringBuilder (datasize);
50
Wuyi if (!internetgetcookie (uri.tostring (), NULL, Cookiedata, ref datasize))
52 {
Errcode = GetLastError ();
The return null;
55}
56
57
58}
59
if (Cookiedata.length > 0)
61 {
cookie = new Cookiecontainer ();
String[] cooks = cookiedata.tostring (). Split (';');
for (int i = 0; i < cooks.length; i++)
65 {
if (Cooks[i].indexof (', ') = = 1)
Cookies.setcookies (URI, cooks[i]);
68}
69}
return cookies;
71}
72
public static string getcookiesstring (Cookiecontainer cookies, Uri Uri)
74 {
if (cookies = null | | | uri = NULL)
"";
cookiecollection cc = cookies.getcookies (URI);
78
Szcookies = "";
-foreach (Cookie cook in cc)
81 {
Szcookies = szcookies + cook.name + "=" + Cook.value + ";";
83}
84
return szcookies;
86}
87
88}
The public static class HTTP
90 {
[DllImport ("Wininet.dll", CharSet = CharSet.Auto, SetLastError = True)]
The public static extern bool InternetSetCookie (string lpszurlname, String lbszcookiename, string lpszcookiedata);
///<summary>
94///to get a page with a POST request
///</summary>
///<param name= "target" > Target address </param>
///<param name= "refere" > Request source </param>
///<param name= "Cookie" >cookie</param>
///<param name= "parameters" > Parameter list </param>
///<returns></returns>
The public static string getposthtml (string target, string refere, ref string cookie, params string[] parameters)
102 {
gethtml return (target, refere, ref cookie, Httprequesttype.post, encoding.getencoding ("gb2312"),%, false , parameters);
104}
The public static string Getposthtmlpar (string target, string refere, ref string cookie, string parameters)
106 {
string[] args = null;
108 if (Parameters!= null)
109 args = Parameters.split (new string[] {"&"}, Stringsplitoptions.none);
Getposthtml (target, refere, ref cookie, args);
111}
112 public static string Gethtmlpar (string target, string refere, ref string cookie, string parameters)
113 {
114 string[] args = null;
(Parameters!= Null)
116 args = Parameters.split (new string[] {"&"}, Stringsplitoptions.none);
117 return gethtml (target, refere, ref cookie, Httprequesttype.get, encoding.getencoding ("gb2312"),%, false, args);
118}
119///<summary>
120///A page with a GET request
121///</summary>
122///<param name= "target" > Destination address </param>
123///<param name= "refere" > Request source </param>
124///<param name= "Cookie" >cookie</param>
///<param name= "parameters" > Parameter list </param>
126///<returns></returns>
127 public static string gethtml (string target, string refere, ref string cookie, params string[] parameters)
128 {
129 return gethtml (target, refere, ref cookie, Httprequesttype.get, encoding.getencoding ("gb2312"),%, false, parameters);
130}
131///<summary>
132///Get a stream
///</summary>
134///<param name= "target" > Destination address </param>
135///<param name= "refere" > Request source </param>
136///<param name= "Cookie" >cookie</param>
137///<param name= "parameters" > Parameter list </param>
138///<param name= "encoding" > Coding </param>
139///<param Name= "Timeout" > timeout </param>
140///<param name= "KeepAlive" > whether to establish a continuous connection </param>
///<param name= "method" > Request type </param>
MB///<returns></returns>
143 public static stream GetStream (string target, string refere, ref string cookie, Httprequesttype method, Encod ING encoding, int timeout, bool keepalive, params string[] parameters)
144 {
145 HttpWebResponse response = null;
146 stream responsestream = null;
147 stream returnstream = null;
148 Try
149 {
string ps = "";
151 if (Parameters!= null && parameters.length >= 1) {PS = String.Join ("&", parameters); }
152
153 byte[] bytes = Encoding.GetBytes (PS);
154 String urlpath = "";
(method = = Httprequesttype.get)
156 {
157 if (Target.indexof ("randcode.jsp tutorial? che=") < 0)
158 {
159 URLPath = String.Format ("{0}?{ 1} ", Target, PS);
160}
161 Else
162 {
163 URLPath = target;
164}
165}
166 Else
167 {
URLPath = target;
169}
170 HttpWebRequest request = (HttpWebRequest) webrequest.create (URLPath);
171
172 Httprequestcachepolicy policy = new Httprequestcachepolicy (Httprequestcachelevel.nocachenostore);
173 Request.cachepolicy = policy;
174 Request.timeout = timeout * 0X3E8;
175 request.keepalive = keepalive;
176 Request.method = Method.tostring (). ToUpper ();
177 bool Ispost = false;
178
179 ispost = request.method.toupper () = = "POST";
180
181 if (ispost)
182 {
183 Request.contenttype = "application/x-www-form-urlencoded";
184 request.contentlength = Bytes.length;
185}
186 request.useragent = "mozilla/4.0" (compatible; MSIE 7.0; Windows NT 5.1; Sv1. NET CLR 2.0.1124) ";
187 Request.referer = Refere;
188 Request.headers.add ("cookie", cookie);
189 Request.headers.add ("Cache-control", "No-cache");
190 request.accept = "*/*";
191 request.credentials = CredentialCache.DefaultCredentials;
if (ispost)
193 {
194 Stream requeststream = Request.getrequeststream ();
195 requeststream.write (Bytes, 0, bytes.length);
196 Requeststream.close ();
197}
198 response = (HttpWebResponse) request.getresponse ();
199 responsestream = Response.getresponsestream ();
200
201 byte[] Buffer = streamtobytes (responsestream);
202
203 Returnstream = new MemoryStream (buffer);
204 String Outcookie = Response.headers.get ("Set-cookie");
205 if (Outcookie!= null)
206 {
207 Outcookie = Outcookie.replace (", jsessionid=", "; Jsessionid= ");
The cookie = setcookies (cookie, Outcookie);
209}
210}
211 catch (Exception)
212 {
213 returnstream = null;
214}
215 finally
216 {
217 if (response!= null)
218 Response.close ();
219 if (responsestream!= null)
Responsestream.close ();
221}
222 return Returnstream;
223
224}
private static byte[] Streamtobytes (Stream stream)
226 {
list<byte> bytes = new list<byte> ();
228 int temp = Stream.readbyte ();
229 while (temp!=-1)
230 {
231 Bytes.add ((byte) temp);
232 temp = Stream.readbyte ();
233}
234
235 return Bytes.toarray ();
236}
237 public static string setcookies (string cookies, String setcookies)
238 {
239 dictionary<string, string> newcookies = new dictionary<string, string> ();
if (Cookies!= null)
241 {
242 string[] Tmpcookies = Cookies.split (";"). ToCharArray ());
243 for (int i = 0; i < tmpcookies.length; i++)
244 {
245 string[] Cookie = tmpcookies[i].split (' = ');
246 if (cookie.length!= 2)
247 continue;
248 Newcookies.add (Cookie[0].trim (), cookie[1]);
249}
250}
251
252 if (setcookies!= null)
253 {
254 string[] tmpcookies = Setcookies.split (";"). ToCharArray ());
255 for (int i = 0; i < tmpcookies.length; i++)
256 {
257 string[] Cookie = tmpcookies[i].split (' = ');
258 if (Cookie.length!= 2)
259 continue;
[Newcookies.containskey (Cookie[0].trim ()) = = False)
261 Newcookies.add (Cookie[0].trim (), cookie[1]);
262 Else
263 Newcookies[cookie[0].trim ()] = cookie[1];
264}
265}
266
267 string sznewcookies = "";
268 dictionary<string, String>.enumerator it = Newcookies.getenumerator ();
while (It.movenext ())
270 {
271 sznewcookies = sznewcookies + "" + it.current.key + "=" + It.current.value + ";";
272}
273
274 if (sznewcookies.length!= 0)
275 sznewcookies = sznewcookies.substring (1, sznewcookies.length-1);
276 return sznewcookies;
277}
278///<summary>
279///get an HTML source
280///</summary>
281///<param name= "target" > Destination address </param>
282///<param name= "refere" > Request source </param>
283///<param name= "Cookie" >cookie</param>
284///<param name= "parameters" > Parameter list </param>
285///<param name= "encoding" > Coding </param>
286///<param name= "Timeout" > timeout </param>
287///<param name= "KeepAlive" > whether to establish a continuous connection </param>
///<param name= "method" > Request type </param>
289///<returns></returns>
290 public static string gethtml (string target, string refere, ref string cookie, Httprequesttype method, Encodin g encoding, int timeout, bool keepalive, params string[] parameters)
291 {
292 string returnhtml = String.Empty;
293 stream stream = null;
294 try
295 {
296 stream = GetStream (target, refere, ref cookie, method, encoding, timeout, keepalive, parameters);
297
298 returnhtml = new StreamReader (stream, encoding). ReadToEnd ();
299}
The catch (Exception)
301 {
302 returnhtml = String.Empty;
303}
304 finally
305 {
306 if (stream!= null)
307 {
308 Stream.Close ();
309}
310}
311 return returnhtml;
312
313}
///<summary>
315///Get a picture
316///</summary>
317///<param name= "target" > Destination address </param>
318///<param name= "refere" > Request source </param>
319///<param name= "Cookie" >cookie</param>
///<param name= "method" > Request type </param>
321///<returns></returns>
322 public static bitmap GetImage (string target, string refere, ref string cookie, Httprequesttype method)
323 {
324 return GetImage (target, refere, ref cookies, method, Encoding.GetEncoding ("gb2312"), true);
325}
326///<summary>
327///Get a picture
328///</summary>
329///<param name= "target" > Destination address </param>
///<param name= "refere" > Request source </param>
331///<param name= "Cookie" >cookie</param>
332///<param Name= "method" > Request type </param>
333///<param name= "encoding" > Coding </param>
334///<param name= "Timeout" > timeout </param>
335///<param name= "KeepAlive" > whether to establish a continuous connection </param>
336///<returns></returns>
337 public static bitmap GetImage (string target, string refere, ref string cookies, Httprequesttype method, Encodi NG encoding, int timeout, bool keepalive, params string[] parameters)
338 {
339 bitmap returnmap = null;
The n-stream stream = null;
341 Try
342 {
343 stream = GetStream (target, refere, ref cookie, method, encoding, timeout, keepalive, parameters);
344 byte[] buf = new Byte[stream.length];
345 stream.read (buf, 0, (int) stream.length);
346 Returnmap = new Bitmap (Image.fromstream (stream));
347}
348 catch (Exception)
349 {
Returnmap = null;
351}
352 finally
353 {
354 if (stream!= null)
355 {
356 Stream.Close ();
357}
358}
359 return returnmap;
360}
361
362 public static HttpStatusCode Getresponsestatuscode (string strurl, String Strcookieheader, string strreferer, O UT string responseurl, out string page
363 {
364 try
365 {
366 HttpWebRequest myhttpwebrequest = (HttpWebRequest) webrequest.create (strURL);
367 Myhttpwebrequest.contenttype = "text/html";
368 Myhttpwebrequest.method = "get";
369 myhttpwebrequest.referer = Strreferer;
370 Myhttpwebrequest.headers.add ("Cookie:" + strcookieheader);
371
372 HttpWebResponse response = (HttpWebResponse) myhttpwebrequest.getresponse ();
373 Responseurl = response.responseuri.originalstring;
374 StreamReader sr = new System.IO.StreamReader (Response.getresponsestream (), encoding.getencoding ("gb231 2 "));
375 page = Sr.readtoend ();
376 return Response.statuscode;
377}
378 catch (Exception ex)
379 {
380
381 Responseurl = "";
382 page = "";
383 return httpstatuscode.requesttimeout;
384}
385}
386
387 public static string Getpostxml (string strurl, String Strargs, String Strcookieheader, String strreferer)
388 {
389 webclient mywebclient = new WebClient ();
390 string postdata = null;
391 byte[] ByteArray;
392 byte[] Responsearray;
393 WebHeaderCollection mywebheadercollection;
394
395 try
396 {
397 ByteArray = encoding.utf8.getbytes (Strargs);
398
399 PostData = Strargs;
Mywebclient.headers.add ("Content-type", "Text/xml");
401 Mywebclient.headers.add ("Referer", strreferer);
402 Mywebclient.headers.add ("Accept-language", "ZH-CN");
403 Mywebclient.headers.add ("ContentLength", bytearray.length.tostring ());
404 Mywebclient.headers.add (Httprequestheader.cookie, Strcookieheader);
50T
406 mywebheadercollection = mywebclient.headers;
407
408 Responsearray = Mywebclient.uploaddata (strURL, "post", ByteArray);
409
410 return encoding.default.getstring (Responsearray);
411}
412 catch (Exception ex)
413 {
414
415 return "";
416}
417}
418 #region Assistant Method
419
420 private static string patternregion = "<input[^>]*?b[^>]*?bname=['"]? {0} [']?b[^>]*?value=[']? (? <value>[^ "]*") [']?b[^>]*?> ';
421//Return point
422 private static string regbackpoint = "<span id= span_fee_0_0" >d+ (. d{1,2})) ((D+ () (d+| (. d{1,2}))) ";
423
424 public static string updateamountsql = "Update orders set Payamount = ' {0} ' where Bigcode = ' {1} '";
425 private static readonly RegexOptions RegexOptions = Regexoptions.singleline | Regexoptions.ignorecase | regexoptions.compiled;
426
427 public static string Findvaluebyname (String strhtml, String elementname)
428 {
429 string strvalue = "";
430 Regex regexregion = new Regex (String.Format (patternregion, elementname), regexoptions); Analysis of regular region
431 try
432 {
433 MatchCollection mc = regexregion.matches (strhtml); strHTML for the page code to parse
434 foreach (Match m in MC)
435 {
436 strvalue = m.groups["value"].value;//the values of the named group to which the match is taken
437}
438}
439 catch (Exception ex)
440 {
64s
442}
443 return strvalue;
444}
445 public static string changereturnhtml (String strhtml)
446 {
447 int begin = 0;
448 int end = 0;
449 while (begin!=-1)
450 {
451 begin = Strhtml.toupper (). indexof ("<script". ToUpper ());
452 end = Strhtml.toupper (). indexof ("</script>". ToUpper ());
453 if (begin!=-1)
454 strhtml = Strhtml.remove (begin, End-begin + 9);
455}
55W
457 strhtml = Moveonload (strhtml);
458
459 return strhtml;
460}
461///<summary>
462///Removes the OnLoad event from the return HTML
463///</summary>
464///<param name= "inputstring" > Return html</param>
465///<returns> Html</returns> after treatment
466 private static string Moveonload (String inputstring)
467 {
468 int begin = 0;
469 int end = 0;
470 String _input = "";
471
472 while (begin!=-1)
473 {
474
475 if (Inputstring.contains ("onload"))
476 {
477 _input = inputstring.substring (Inputstring.indexof ("onload"));
478
479 begin = _input.indexof ("onload");
The end = _input.indexof (">");
481 if (Begin!=-1 && End!=-1)
482 {
483 _input = _input.substring (begin, End-begin + 1);
484 inputstring = Inputstring.replace (_input, "");
485}
486}
487 Else
488 begin =-1;
489}
490 return inputstring;
491}
492 public static string geturlcookies (string url, string cookiename)
493 {
494 uri uri = new uri (URL);
495 Cookiecontainer cc = Cookiemanger.geturicookiecontainer (URI);
496 return cookiemanger.getcookiesstring (cc, URI);
497}
498 public static string GetSessionID (String cookies)
499 {
//match match = Regex.match (cookies, @) (? <sessionid>jsessionid=) ([^;] *)) ", regexoptions.ignorecase);
501 Try
502 {
503 match = Regex.match (cookies, @ "<sessionid>[^;,s]*sessionid=[^;] *) ", regexoptions.ignorecase);
504 if (match.success = = True)
505 return match.groups["SessionID"].value.trim ();
506 Else
507 return "";
508}
509 catch (Exception ex)
510 {
511
Return "";
513}
514}
515 public static void Seturlcookies (string url, string cookie)
516 {
517 if (Cookies!= null)
518 {
519 string[] tmpcookies = Cookies.split (";"). ToCharArray ());
520//stringbuilder sbcookiename = new StringBuilder ();
521//stringbuilder sbcookievalue = new StringBuilder ();
522
523 uri uri = new uri (URL);
524 for (int i = 0; i < tmpcookies.length; i++)
525 {
526 string[] Cookie = tmpcookies[i].split (' = ');
527 if (cookie.length!= 2)
528 continue;
529//sbcookiename.append (cookie[0]);
530//sbcookievalue.append (cookie[1]);
531
532 InternetSetCookie (URL, cookie[0], cookie[1]/*+ "; expires=sun,22-feb-2099 00:00:00 GMT;" */);
//internetsetcookie (URL, "", "");
534}
535
536//internetsetcookie (URL, sbcookiename, sbcookievalue);
537}
538}
539 public static string Findbackpoint (String strhtml)
540 {
541 regex regs = new Regex (regbackpoint);
542 return Regs.match (strhtml). Groups[3].value;
543}
544 #endregion
545}
546}
Create a simple cookie:string cookiename= "Visittimes" in a JSP; Cookie Cookie=new Cookie (cookiename, "1"); Cookie.setmaxage (10*60)//Set cookie Lifetime Cookie.addcookie (cookie);//write cookies to the client in the JSP processing cookie Data Common method: GetDomain (); Returns the domain name of the cookie. Getmaxage (); Returns the cookie's surviving time getname (); Returns the name of the cookie GetPath (); Returns the path Getsecure () to which the cookie applies, and returns a true value if the browser sends a cookie over the security protocol. If the browser uses the standard protocol just returns the value of False GetValue (), returns the value of the cookie GetVersion (), returns the Protocol version setcomment (string purpose) that the cookie complies with, and sets the comment se for the cookie Tpath (string URL), set the appropriate path for the cookie SetSecure (Boolean flag), and set whether the browser only uses the security protocol to send cookies, such as using HTTPS or SSL SetValue (string NewValue), set a new value setversion (int v) After the cookie is created, and set the protocol version that the cookie complies with.