【asp.net core】asp.net http 获取 cookie

更新时间:2016-12-14    来源:安全加密    手机版     字体:

【www.bbyears.com--安全加密】

asp教程.net http 获取 cookie

cookie,有时也用其复数形式cookies,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)。定义于rfc2109(已废弃),最新取代的规范是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教程ervices;
 10
 11 namespace httpsimulation
 12 {
 13     ///


 14     /// 访问网络的方法
 15     ///

 16     public enum httprequesttype
 17     {
 18         ///
 19         /// post请求
 20         ///

 21         post,
 22         ///
 23         /// get请求
 24         ///

 25         get
 26     }
 27     ///
 28     /// 获取cookie的方法类。
 29     ///

 30     public class cookiemanger
 31     {
 32         [dllimport("wininet.dll", setlasterror = true)]
 33         public static extern bool internetgetcookie(string url, string cookiename, stringbuilder cookiedata, ref int size);
 34         [dllimport("kernel32.dll", setlasterror = true)]
 35         private static extern int getlasterror();
 36
 37         public static cookiecontainer geturicookiecontainer(uri uri)
 38         {
 39             cookiecontainer cookies = null;
 40             //定义cookie数据的大小。
 41             int datasize = 256;
 42             stringbuilder cookiedata = new stringbuilder(datasize);
 43
 44             if (!internetgetcookie(uri.tostring(), null, cookiedata, ref datasize))
 45             {
 46                 int errcode = getlasterror();
 47                 if (datasize < 0)
 48                     return null; // 确信有足够大的空间来容纳cookie数据。
 49                 cookiedata = new stringbuilder(datasize);
 50
 51                 if (!internetgetcookie(uri.tostring(), null, cookiedata, ref datasize))
 52                 {
 53                     errcode = getlasterror();
 54                     return null;
 55                 }
 56
 57
 58             }
 59
 60             if (cookiedata.length > 0)
 61             {
 62                 cookies = new cookiecontainer();
 63                 string[] cooks = cookiedata.tostring().split(";");
 64                 for (int i = 0; i < cooks.length; i++)
 65                 {
 66                     if (cooks[i].indexof(",") == -1)
 67                         cookies.setcookies(uri, cooks[i]);
 68                 }
 69             }
 70             return cookies;
 71         }
 72
 73         public static string getcookiesstring(cookiecontainer cookies, uri uri)
 74         {
 75             if (cookies == null || uri == null)
 76                 return "";
 77             cookiecollection cc = cookies.getcookies(uri);
 78
 79             string szcookies = "";
 80             foreach (cookie cook in cc)
 81             {
 82                 szcookies = szcookies + cook.name + "=" + cook.value + ";";
 83             }
 84
 85             return szcookies;
 86         }
 87
 88     }
 89     public static class http
 90     {
 91         [dllimport("wininet.dll", charset = charset.auto, setlasterror = true)]
 92         public static extern bool internetsetcookie(string lpszurlname, string lbszcookiename, string lpszcookiedata);
 93         ///
 94         /// 以post请求获取一个页面
 95         ///

 96         /// 目标地址
 97         /// 请求源
 98         /// cookie
 99         /// 参数列表
100         ///
101         public static string getposthtml(string target, string refere, ref string cookie, params string[] parameters)
102         {
103             return gethtml(target, refere, ref cookie, httprequesttype.post, encoding.getencoding("gb2312"), 60, false, parameters);
104         }
105         public static string getposthtmlpar(string target, string refere, ref string cookie, string parameters)
106         {
107             string[] args = null;
108             if (parameters != null)
109                 args = parameters.split(new string[] { "&" }, stringsplitoptions.none);
110             return 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;
115             if (parameters != null)
116                 args = parameters.split(new string[] { "&" }, stringsplitoptions.none);
117             return gethtml(target, refere, ref cookie, httprequesttype.get, encoding.getencoding("gb2312"), 60, false, args);
118         }
119         ///
120         /// 以get请求获取一个页面
121         ///

122         /// 目标地址
123         /// 请求源
124         /// cookie
125         /// 参数列表
126         ///
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"), 60, false, parameters);
130         }
131         ///
132         /// 获取一个stream
133         ///

134         /// 目标地址
135         /// 请求源
136         /// cookie
137         /// 参数列表
138         /// 编码
139         /// 超时时间
140         /// 是否建立持续连接
141         /// 请求类型
142         ///
143         public static stream getstream(string target, string refere, ref  string cookie, httprequesttype method, encoding encoding, int timeout, bool keepalive, params string[] parameters)
144         {
145             httpwebresponse response = null;
146             stream responsestream = null;
147             stream returnstream = null;
148             try
149             {
150                 string ps = "";
151                 if (parameters != null && parameters.length >= 1) { ps = string.join("&", parameters); }
152
153                 byte[] bytes = encoding.getbytes(ps);
154                 string urlpath = "";
155                 if (method == httprequesttype.get)
156                 {
157                     if (target.indexof("randcode.jsp教程?che=") < 0)
158                     {
159                         urlpath = string.format("{0}?{1}", target, ps);
160                     }
161                     else
162                     {
163                         urlpath = target;
164                     }
165                 }
166                 else
167                 {
168                     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;
192                 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=");
208                     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)
220                     responsestream.close();
221             }
222             return returnstream;
223
224         }
225         private static byte[] streamtobytes(stream stream)
226         {
227             list bytes = new list();
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 newcookies = new dictionary();
240             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;
260                     if (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.enumerator it = newcookies.getenumerator();
269             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         ///
279         /// 获取一个html源
280         ///

281         /// 目标地址
282         /// 请求源
283         /// cookie
284         /// 参数列表
285         /// 编码
286         /// 超时时间
287         /// 是否建立持续连接
288         /// 请求类型
289         ///
290         public static string gethtml(string target, string refere, ref  string cookie, httprequesttype method, encoding 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             }
300             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         }
314         ///
315         /// 获取一张图片
316         ///

317         /// 目标地址
318         /// 请求源
319         /// cookie
320         /// 请求类型
321         ///
322         public static bitmap getimage(string target, string refere, ref  string cookie, httprequesttype method)
323         {
324             return getimage(target, refere, ref cookie, method, encoding.getencoding("gb2312"), 60, true);
325         }
326         ///
327         /// 获取一张图片
328         ///

329         /// 目标地址
330         /// 请求源
331         /// cookie
332         /// 请求类型
333         /// 编码
334         /// 超时时间
335         /// 是否建立持续连接
336         ///
337         public static bitmap getimage(string target, string refere, ref  string cookie, httprequesttype method, encoding encoding, int timeout, bool keepalive, params string[] parameters)
338         {
339             bitmap returnmap = null;
340             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             {
350                 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, out 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("gb2312"));
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;
400                 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);
405
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 辅助方法
419
420         private static string patternregion = "]*?b[^>]*?bname=[""]?{0}[""]?b[^>]*?value=[""]?(?[^"]*)[""]?b[^>]*?>";
421         //返点
422         private static string regbackpoint = "d+(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); //解析region的正则
431             try
432             {
433                 matchcollection mc = regexregion.matches(strhtml); //strhtml为要分析的网页代码
434                 foreach (match m in mc)
435                 {
436                     strvalue = m.groups["value"].value;//取匹配到的命名组的值
437                 }
438             }
439             catch (exception ex)
440             {
441                
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             }
456
457             strhtml = moveonload(strhtml);
458
459             return strhtml;
460         }
461         ///
462         /// 移除返回html中的onload事件
463         ///

464         /// 返回的html
465         /// 处理后的html
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");
480                     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         {
500             //match match = regex.match(cookies, @"(?jsessionid=([^;]*))", regexoptions.ignorecase);
501             try
502             {
503                 match match = regex.match(cookies, @"(?[^;,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                
512                 return "";
513             }
514         }
515         public static void seturlcookies(string url, string cookies)
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;"*/);
533                     //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 }

    

使用cookie实现单点登录
[1]cookie是由服务器端生成,发送给user-agent(一般是浏览器),浏览器会将cookie的key/value保存到某个目录下的文本文件内,下次请求同一网站时就发送该cookie给服务器(前提是浏览器设置为启用cookie)。cookie名称和值可以由服务器端开发自己定义,对于jsp而言也可以直接写入jsessionid,这样服务器可以知道该用户是否合法用户以及是否需要重新登录等。

在jsp中创建简单的cookie:   string cookiename="visittimes";   cookie cookie=new cookie(cookiename,"1");   cookie.setmaxage(10*60);//设置cookie存活期   cookie.addcookie(cookie);//将cookie写入客户端   在jsp中处理cookie数据的常用方法:   getdomain();返回cookie的域名.   getmaxage();返回cookie的存活时间   getname();返回cookie的名字   getpath();返回cookie适用的路径   getsecure();如果浏览器通过安全协议发送cookie将返回true值,如果浏览器使用标准协议刚返回false值   getvalue();返回cookie的值   getversion();返回cookie所遵从的协议版本   setcomment(string purpose);设置cookie的注释   setpath(string url);设置cookie的适用路径   setsecure(boolean flag);设置浏览器是否仅仅使用安全协议来发送cookie,例如使用https或ssl   setvalue(string newvalue);cookie创建后设置一个新的值   setversion(int v);设置cookie所遵从的协议版本.

本文来源:http://www.bbyears.com/aspjiaocheng/29006.html

猜你感兴趣

热门标签

更多>>

本类排行