最近在做一個通過HttpWebRequest來實現(xiàn)登陸和自動發(fā)信息的小軟件,雖然還沒有實現(xiàn),但是今天從一個老外的網(wǎng)站上看到了一個獲取CookieContainer很好的方法,拿出來共享一下,這是我看到過代碼最少而且很不錯的了。
1using System;
2using System.Runtime.InteropServices;
3using System.Text;
4using System.Net;
5
6namespace NExplus.NSiter
7{
8 /**////
9 /// 獲取Cookie的方法類。
10 ///
11 public class CookieManger
12 {
13 /**////
14 /// 通過COM來獲取Cookie數(shù)據(jù)。
15 ///
16 /// 當(dāng)前網(wǎng)址。
17 /// CookieName.
18 /// 用于保存Cookie Data的 實例。
19 /// Cookie大小。
20 ///如果成功則返回true ,否則返回false 。
21 [DllImport("wininet.dll", SetLastError = true)]
22 public static extern bool InternetGetCookie(
23 string url, string cookieName,
24 StringBuilder cookieData, ref int size);
25 /**////
26 /// 獲取當(dāng)前 的 實例。
27 ///
28 /// 當(dāng)前 地址。
29 ///當(dāng)前 的 實例。
30 public static CookieContainer GetUriCookieContainer(Uri uri) {
31 CookieContainer cookies = null;
32
33 // 定義Cookie數(shù)據(jù)的大小。
34 int datasize = 256;
35 StringBuilder cookieData = new StringBuilder(datasize);
36
37 if (!InternetGetCookie(uri.ToString(), null, cookieData,
38 ref datasize)) {
39 if (datasize < 0)
40 return null;
41
42 // 確信有足夠大的空間來容納Cookie數(shù)據(jù)。
43 cookieData = new StringBuilder(datasize);
44 if (!InternetGetCookie(uri.ToString(), null, cookieData,
45 ref datasize))
46 return null;
47 }
48
49
50 if (cookieData.Length > 0) {
51 cookies = new CookieContainer();
52 cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
53 }
54 return cookies;
55 }
56
57 }
58} 是不是相當(dāng)簡單阿,希望對大家有一點用處。
1using System;
2using System.Runtime.InteropServices;
3using System.Text;
4using System.Net;
5
6namespace NExplus.NSiter
7{
8 /**////
9 /// 獲取Cookie的方法類。
10 ///
11 public class CookieManger
12 {
13 /**////
14 /// 通過COM來獲取Cookie數(shù)據(jù)。
15 ///
16 /// 當(dāng)前網(wǎng)址。
17 /// CookieName.
18 /// 用于保存Cookie Data的
19 /// Cookie大小。
20 ///
21 [DllImport("wininet.dll", SetLastError = true)]
22 public static extern bool InternetGetCookie(
23 string url, string cookieName,
24 StringBuilder cookieData, ref int size);
25 /**////
26 /// 獲取當(dāng)前
27 ///
28 /// 當(dāng)前
29 ///
30 public static CookieContainer GetUriCookieContainer(Uri uri) {
31 CookieContainer cookies = null;
32
33 // 定義Cookie數(shù)據(jù)的大小。
34 int datasize = 256;
35 StringBuilder cookieData = new StringBuilder(datasize);
36
37 if (!InternetGetCookie(uri.ToString(), null, cookieData,
38 ref datasize)) {
39 if (datasize < 0)
40 return null;
41
42 // 確信有足夠大的空間來容納Cookie數(shù)據(jù)。
43 cookieData = new StringBuilder(datasize);
44 if (!InternetGetCookie(uri.ToString(), null, cookieData,
45 ref datasize))
46 return null;
47 }
48
49
50 if (cookieData.Length > 0) {
51 cookies = new CookieContainer();
52 cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
53 }
54 return cookies;
55 }
56
57 }
58} 是不是相當(dāng)簡單阿,希望對大家有一點用處。