using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace HttpClient
{
///
/// 通过Http协议访问Web
///
public class HttpClient
{
#region Cookie集合
///
/// Cookie集合
///
private CookieContainer cookies;
#endregion
#region Http user-agent标头值
///
/// Http user-agent标头值
///
public string UserAgent { get; set; }
#endregion
#region HttpClient构造函数
public HttpClient()
{
this.cookies = new CookieContainer();
}
#endregion
#region 获取HttpClient的Cookie集合
///
/// 获取HttpClient的Cookie集合
///
///
public CookieContainer GetCookieContainer()
{
return this.cookies;
}
#endregion
#region 设置HttpClient的Cookie集合
///
/// 设置HttpClient的Cookie集合
///
/// Cookie集合对象
/// True设置成功 False设置失败
public bool SetCookieContainer(CookieContainer _cookie)
{
if (_cookie != null)
{
this.cookies = _cookie;
return true;
}
return false;
}
#endregion
#region 以GET方式打开一个Http连接
///
/// 以GET方式打开一个Http连接
///
/// 地址
/// 请求头
///
public ResultResponse OpenGetUrl(string url, Dictionary headers)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = this.cookies;
request.Method = HttpClient.ConnectionType.GET;
request.KeepAlive = true;
if (this.UserAgent != null && this.UserAgent != "")
{
request.UserAgent = this.UserAgent;
}
this.FillHeaders(request, headers);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return new ResultResponse(response);
}
#endregion
#region 以GET方式打开一个Http连接,302自定义处理行为
///
/// 以GET方式打开一个Http连接,302自定义处理行为
///
/// 地址
/// 请求头
/// 302跳转处理
///
public ResultResponse OpenGetUrlRedirect(string url, Dictionary headers,HttpClient.RedirectAction action)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = this.cookies;
request.Method = HttpClient.ConnectionType.GET;
request.KeepAlive = true;
request.AllowAutoRedirect = false; //302不采用默认行为处理
if (this.UserAgent != null && this.UserAgent != "")
{
request.UserAgent = this.UserAgent;
}
this.FillHeaders(request, headers);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
ResultResponse result=new ResultResponse(response);
if (response.StatusCode == HttpStatusCode.Found)
{
bool ret = true;
if (action != null)
{
ret = action(result);
}
string locationurl = response.Headers["Location"];
if (ret == true)
{
return this.OpenGetUrlRedirect(locationurl, null, action);
}
return result;
}
return result;
}
#endregion
#region Http 302跳转处理
///
/// Http 302跳转处理
///
/// 响应对象
/// False 不继续跳转 True继续跳转
public delegate bool RedirectAction(ResultResponse result);
#endregion
#region 将Http标头值添加到Request对象中
///
/// 将Http标头值添加到Request对象中
///
///
private void FillHeaders(HttpWebRequest request,Dictionary headers)
{
if (headers != null && headers.Count > 0)
{
Dictionary.Enumerator em = headers.GetEnumerator();
while (em.MoveNext())
{
request.Headers.Add(em.Current.Key, em.Current.Value);
}
}
}
#endregion
#region 以POST方式打开一个Http连接
///
/// 以POST方式打开一个Http连接
///
/// 地址
/// 请求头
/// 发送的数据
///
public ResultResponse OpenPostUrl(string url,Dictionary headers,Dictionary data)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = this.cookies;
request.Method = HttpClient.ConnectionType.POST;
request.KeepAlive = true;
if (this.UserAgent != null && this.UserAgent != "")
{
request.UserAgent = this.UserAgent;
}
this.FillHeaders(request, headers);
byte[] buff = DictToBytes(data);
request.GetRequestStream().Write(buff, 0, buff.Length);
request.GetRequestStream().Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return new ResultResponse(response);
}
#endregion
#region 以POST方式打开一个Http连接,302自定义处理行为
///
/// 以POST方式打开一个Http连接,302自定义处理行为
///
/// 地址
/// 请求头
/// 发送的数据
/// 302自定义处理
///
public ResultResponse OpenPostUrlRedirect(string url, Dictionary headers, Dictionary data,HttpClient.RedirectAction action)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = this.cookies;
request.Method = HttpClient.ConnectionType.POST;
request.KeepAlive = true;
request.AllowAutoRedirect = false;
if (this.UserAgent != null && this.UserAgent != "")
{
request.UserAgent = this.UserAgent;
}
this.FillHeaders(request, headers);
byte[] buff = DictToBytes(data);
request.GetRequestStream().Write(buff, 0, buff.Length);
request.GetRequestStream().Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
ResultResponse result = new ResultResponse(response);
if (response.StatusCode == HttpStatusCode.Found)
{
bool ret = true;
if (action != null)
{
ret = action(result);
}
string locationurl = response.Headers["Location"];
return result;
}
return result;
}
#endregion
#region 将字典的key和value拼接成http参数
///
/// 将字典的key和value拼接成http参数
///
/// 参数
///
private byte[] DictToBytes(Dictionary dic)
{
StringBuilder sb = null;
if (dic != null)
{
Dictionary.Enumerator em= dic.GetEnumerator();
sb = new StringBuilder();
while (em.MoveNext())
{
sb.Append(String.Format("{0}={1}&", em.Current.Key, em.Current.Value));
}
return System.Text.Encoding.UTF8.GetBytes(sb.ToString());
}
return null;
}
#endregion
#region HttpClient打开连接的方式
///
/// HttpClient打开连接的方式
///
public static class ConnectionType
{
public static string GET { get { return "GET"; } }
public static string POST { get { return "POST"; } }
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace HttpClient
{
///
///包含服务器响应数据的对象
///
public class ResultResponse
{
#region HttpWebResponse对象
///
/// HttpWebResponse对象
///
private HttpWebResponse m_response;
#endregion
#region 创建一个HttpWebResponse对象
///
/// 创建一个HttpWebResponse对象
///
/// HttpWebResponse
public ResultResponse(HttpWebResponse _response)
{
this.m_response = _response;
}
#endregion
#region 获取响应内容的二进制流
///
/// 获取响应内容的二进制流
///
///
public Stream GetResponseStream()
{
if (this.m_response != null)
{
return this.m_response.GetResponseStream();
}
return null;
}
#endregion
#region Http版本
///
/// Http版本
///
public string ProtocolVersion { get { return this.m_response != null ? this.m_response.ProtocolVersion.ToString() : ""; } }
#endregion
///
/// 响应方法
///
public string Method { get { return this.m_response != null ? this.m_response.Method : ""; } }
///
/// Http状态码
///
public string StatusCode { get { return this.m_response != null ? this.m_response.StatusCode.ToString() : ""; } }
///
/// Http响应头
///
public WebHeaderCollection Headers { get { return this.m_response != null ? this.m_response.Headers : null;} }
///
/// 响应流的字符编码
///
///
public Encoding getResponseEncoding()
{
if (this.m_response != null)
{
return Encoding.GetEncoding(this.m_response.ContentEncoding);
}
return null;
}
///
/// 获取响应内容的字符串
///
/// 字符串编码(默认utf8)
///
public string GetContent(string encoding="utf-8")
{
return System.Text.Encoding.GetEncoding(encoding).GetString(this.StreamtoBytes(this.GetResponseStream()));
}
///
/// 获取原始的HttpWebResponse
///
///
public HttpWebResponse GetRawResponse()
{
return this.m_response;
}
///
/// 二进制流转换成字节数组
///
///
///
private byte[] StreamtoBytes(Stream _stream)
{
byte[] buff;
int rlen;
MemoryStream _ms;
if (_stream != null)
{
buff = new byte[1024];
rlen = 0;
_ms = new MemoryStream();
while ((rlen = _stream.Read(buff, 0, 1024)) > 0)
{
_ms.Write(buff, 0, rlen);
}
buff = _ms.ToArray();
_ms.Close();
_ms.Dispose();
return buff;
}
return null;
}
}
}