The HttpClient is a helper class for Http request in C#, you can download the original source code from http://read.pudn.com/downloads111/sourcecode/web/463929/HttpClient.cs__.htm
Here is a Chinese version handle book: http://www.tzwhx.com/newOperate/html/1/12/123/8818.html
Tips first, otherwise the source code will overlap these tips:
- All cookies stored in special folder which can be got from “Environment.GetFolderPath(Environment.SpecialFolder.Cookies);”
- All cookies for one single domain are stored in one same plain-text file, the file name format is “[system user name]@domain[sort].txt”
- Each cookies saved in the plain text file separated in 9 lines, the last line is “*", the first line is the name of the cookie, and the second line is the value of the cookie, and the third line is domain name.
- I don’t know how to resolve the date-time/time-stamp from this plain text.
I have do the following enhancements:
- Auto add domain information into cookie in function “CreateRequest()”
private HttpWebRequest CreateRequest()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = false;
req.CookieContainer = new CookieContainer();
req.Headers.Add("Accept-Language", defaultLanguage);
req.Accept = accept;
req.UserAgent = userAgent;
req.KeepAlive = false;
Uri u=req.RequestUri;
if (context.Cookies != null)
{
foreach (Cookie ck in context.Cookies)
{
if (null != ck
&& null!=ck.Name
&& null!=ck.Value
&& ck.Name.Length>0
//&& ck.Value.Length > 0
)
{
if (ck.Domain == null || ck.Domain.Trim().Length < 1)
{
ck.Domain = req.RequestUri.Host;
}
if (ck.Path == null || ck.Path.Length < 1)
{
ck.Path = req.RequestUri.LocalPath;
}
req.CookieContainer.Add(ck);
}
}
}
if (!string.IsNullOrEmpty(context.Referer))
req.Referer = context.Referer;
if (verb == HttpVerb.HEAD)
{
req.Method = "HEAD";
return req;
}
- add a helper function “ParseCookies” into class “HttpClientContext”
public void ParseCookies(string str)
{
if (null == str || str.Trim().Length < 1)
{
return;
}
str=str.Trim();
const string CookiePrefix="Cookie:";
if (str.ToLower().StartsWith(CookiePrefix.ToLower()))
{
str = str.Substring(CookiePrefix.Length).Trim();
}
string[] args = str.Split(';');
foreach (string sp in args)
{
int n = sp.IndexOf('=');
if (n < 0)
{
continue;
}
string name = sp.Substring(0, n).Trim();
if (name.Length < 1)
{
continue;
}
string value = sp.Substring(n + 1).Trim();
if (null == this.cookies)
{
this.cookies = new CookieCollection();
}
this.cookies.Add(new Cookie(name, value));
}
}
I’d like to put one file for download here:
httpclient.cs (16.46 kb)