最近在做一個通過HttpWebRequest來實現登陸和自動發信息的小軟件
雖然還沒有實現
但是今天從一個老外的網站上看到了一個獲取CookieContainer很好的方法
拿出來共享一下
這是我看到過代碼最少而且很不錯的了
using System;
using System
Runtime
InteropServices;
using System
Text;
using System
Net;
namespace NExplus
NSiter
{
/**//// <summary>
/// 獲取Cookie的方法類
/// </summary>
public class CookieManger
{
/**//// <summary>
/// 通過COM來獲取Cookie數據
/// </summary>
/// <param name=
url
>當前網址
</param>
/// <param name=
cookieName
>CookieName
</param>
/// <param name=
cookieData
>用於保存Cookie Data的<see cref=
StringBuilder
/>實例
</param>
/// <param name=
size
>Cookie大小
</param>
/// <returns>如果成功則返回<c>true</c>
否則返回<c>false</c>
</returns>
[DllImport(
wininet
dll
SetLastError = true)]
public static extern bool InternetGetCookie(
string url
string cookieName
StringBuilder cookieData
ref int size);
/**//// <summary>
/// 獲取當前<see cref=
Uri
/>的<see cref=
CookieContainer
/>實例
/// </summary>
/// <param name=
uri
>當前<see cref=
Uri
/>地址
</param>
/// <returns>當前<see cref=
Uri
/>的<see cref=
CookieContainer
/>實例
</returns>
public static CookieContainer GetUriCookieContainer(Uri uri) {
CookieContainer cookies = null;
// 定義Cookie數據的大小
int datasize =
;
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookie(uri
ToString()
null
cookieData
ref datasize)) {
if (datasize <
)
return null;
// 確信有足夠大的空間來容納Cookie數據
cookieData = new StringBuilder(datasize);
if (!InternetGetCookie(uri
ToString()
null
cookieData
ref datasize))
return null;
}
if (cookieData
Length >
) {
cookies = new CookieContainer();
cookies
SetCookies(uri
cookieData
ToString()
Replace(
;
));
}
return cookies;
}
}
} 是不是相當簡單阿
希望對大家有一點用處
l
From:http://tw.wingwit.com/Article/program/net/201311/11322.html