C#下的WebClient保存session和cookie的方法
其实实现方法挺简单,继承到WebClient,然后重写其的相关方法即可了,同时还有针对模拟post提交数据时的编码问题,也遇到了,在提交发表信息的时候,默认的好像是按照本机语言的默认编码?还是什么?具体不大了解,中间修改了下,然后针对GBK和UTF-8,测试OK了.保存下,以后或许用的到.
WebClient保存session代码,重写类
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace DiscuzPost
{
class HttpClient : WebClient
{
// Cookie 容器
private CookieContainer cookieContainer;
/**/
/// <summary>
/// 创建一个新的 WebClient 实例。
/// </summary>
public HttpClient()
{
this.cookieContainer = new CookieContainer();
}
/**/
/// <summary>
/// 创建一个新的 WebClient 实例。
/// </summary>
/// <param name="cookie">Cookie 容器</param>
public HttpClient(CookieContainer cookies)
{
this.cookieContainer = cookies;
}
/**/
/// <summary>
/// Cookie 容器
/// </summary>
public CookieContainer Cookies
{
get { return this.cookieContainer; }
set { this.cookieContainer = value; }
}
/**/
/// <summary>
/// 返回带有 Cookie 的 HttpWebRequest。
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
HttpWebRequest httpRequest = request as HttpWebRequest;
httpRequest.CookieContainer = cookieContainer;
}
return request;
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace DiscuzPost
{
class HttpClient : WebClient
{
// Cookie 容器
private CookieContainer cookieContainer;
/**/
/// <summary>
/// 创建一个新的 WebClient 实例。
/// </summary>
public HttpClient()
{
this.cookieContainer = new CookieContainer();
}
/**/
/// <summary>
/// 创建一个新的 WebClient 实例。
/// </summary>
/// <param name="cookie">Cookie 容器</param>
public HttpClient(CookieContainer cookies)
{
this.cookieContainer = cookies;
}
/**/
/// <summary>
/// Cookie 容器
/// </summary>
public CookieContainer Cookies
{
get { return this.cookieContainer; }
set { this.cookieContainer = value; }
}
/**/
/// <summary>
/// 返回带有 Cookie 的 HttpWebRequest。
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
HttpWebRequest httpRequest = request as HttpWebRequest;
httpRequest.CookieContainer = cookieContainer;
}
return request;
}
}
}
post数据改变其编码
using System;
using System.Collections.Generic;
using System.Text;
namespace DiscuzPost
{
class CharSet
{
public static byte[] get(string charset,string str){
byte[] byteArray;
if ("utf-8".Equals(charset.ToLower()))
{
byteArray = Encoding.UTF8.GetBytes(str);
}
else
{
byteArray = Encoding.Default.GetBytes(str);
}
return byteArray;
}
}
}
using System.Collections.Generic;
using System.Text;
namespace DiscuzPost
{
class CharSet
{
public static byte[] get(string charset,string str){
byte[] byteArray;
if ("utf-8".Equals(charset.ToLower()))
{
byteArray = Encoding.UTF8.GetBytes(str);
}
else
{
byteArray = Encoding.Default.GetBytes(str);
}
return byteArray;
}
}
}