转载自:http://www.sufeinet.com/thread-6-1-1.html
如果你想做一些,抓取,或者是自动获取的功能,那么就跟我一起来学习一下Http请求吧。
本文章会对Http请求时的Get和Post方式进行详细的说明,这个类是专门为HTTP的GET和POST请求写的,解决了编码,证书,自动带Cookie等问题。
get方法
public static string GetUrltoHtml(string Url,string type)
{
try
{
System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
// Get the response instance.
System.Net.WebResponse wResp = wReq.GetResponse();
System.IO.Stream respStream = wResp.GetResponseStream();
// Dim reader As StreamReader = New StreamReader(respStream)
using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
{
return reader.ReadToEnd();
}
}
catch (System.Exception ex)
{
//errorMsg = ex.Message;
}
return "";
}
///
///采用http协议访问网络
///
///url地址
///发送的数据
///
public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding)
{
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "post";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/x-www-form-urlencoded";
byte[] buffer = encoding.GetBytes(strPostdata);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using( StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))
{
return reader.ReadToEnd();
}
}
///
///回调验证证书问题
///
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// 总是接受
return true;
}
///
/// 传入URL返回网页的html代码
///
/// URL
///
public string GetUrltoHtml(string Url)
{
StringBuilder content = new StringBuilder();
try
{
//这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
// 与指定URL创建HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
//创建证书文件
X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer");
//添加到请求里
request.ClientCertificates.Add(objx509);
// 获取对应HTTP请求的响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 获取响应流
Stream responseStream = response.GetResponseStream();
// 对接响应流(以"GBK"字符集)
StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
// 开始读取数据
Char[] sReaderBuffer = new Char[256];
int count = sReader.Read(sReaderBuffer, 0, 256);
while (count > 0)
{
String tempStr = new String(sReaderBuffer, 0, count);
content.Append(tempStr);
count = sReader.Read(sReaderBuffer, 0, 256);
}
// 读取结束
sReader.Close();
}
catch (Exception)
{
content = new StringBuilder("Runtime Error");
}
return content.ToString();
}
///
///回调验证证书问题
///
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// 总是接受
return true;
}
///
///采用http协议访问网络
///
///url地址
///发送的数据
///
public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding)
{
// 这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
//创建证书文件
X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer");
//加载Cookie
request.CookieContainer = new CookieContainer();
//添加到请求里
request.ClientCertificates.Add(objx509);
request.Method = "post";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/x-www-form-urlencoded";
byte[] buffer = encoding.GetBytes(strPostdata);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))
{
return reader.ReadToEnd();
}
}
看代码
get方法
///
/// 传入URL返回网页的html代码带有证书的方法
///
/// URL
///
public string GetUrltoHtml(string Url)
{
StringBuilder content = new StringBuilder();
try
{
// 与指定URL创建HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)";
request.Method = "GET";
request.Accept = "*/*";
//如果方法验证网页来源就加上这一句如果不验证那就可以不写了
request.Referer = "http://sufei.cnblogs.com";
CookieContainer objcok = new CookieContainer();
objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("键", "值"));
objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("键", "值"));
objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233"));
request.CookieContainer = objcok;
//不保持连接
request.KeepAlive = true;
// 获取对应HTTP请求的响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 获取响应流
Stream responseStream = response.GetResponseStream();
// 对接响应流(以"GBK"字符集)
StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312"));
// 开始读取数据
Char[] sReaderBuffer = new Char[256];
int count = sReader.Read(sReaderBuffer, 0, 256);
while (count > 0)
{
String tempStr = new String(sReaderBuffer, 0, count);
content.Append(tempStr);
count = sReader.Read(sReaderBuffer, 0, 256);
}
// 读取结束
sReader.Close();
}
catch (Exception)
{
content = new StringBuilder("Runtime Error");
}
return content.ToString();
}
//////采用https协议访问网络
///
///url地址
///发送的数据
///
public string OpenReadWithHttps(string URL, string strPostdata)
{
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "post";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/x-www-form-urlencoded";
CookieContainer objcok = new CookieContainer();
objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("键", "值"));
objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("键", "值"));
objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233"));
request.CookieContainer = objcok;
byte[] buffer = encoding.GetBytes(strPostdata);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
return reader.ReadToEnd();
}
这就是在你请求后可以得到当次Cookie的方法,直接取得返回给上一个方法使用就行了,上面我们都是自己构造的,在这里直接使用这个Cookie就可以了。response.Cookies
///
/// 传入URL返回网页的html代码
///
/// URL
///
public string GetUrltoHtml(string Url)
{
StringBuilder content = new StringBuilder();
try
{
//这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
// 与指定URL创建HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
//创建证书文件
X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer");
//添加到请求里
request.ClientCertificates.Add(objx509);
CookieContainer objcok = new CookieContainer();
objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("键", "值"));
objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("键", "值"));
objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233"));
request.CookieContainer = objcok;
// 获取对应HTTP请求的响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 获取响应流
Stream responseStream = response.GetResponseStream();
// 对接响应流(以"GBK"字符集)
StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
// 开始读取数据
Char[] sReaderBuffer = new Char[256];
int count = sReader.Read(sReaderBuffer, 0, 256);
while (count > 0)
{
String tempStr = new String(sReaderBuffer, 0, count);
content.Append(tempStr);
count = sReader.Read(sReaderBuffer, 0, 256);
}
// 读取结束
sReader.Close();
}
catch (Exception)
{
content = new StringBuilder("Runtime Error");
}
return content.ToString();
}
request.Referer = "http://sufei.cnblogs.com"
///
/// 过滤html标签
///
/// html的内容
///
public static string StripHTML(string stringToStrip)
{
// paring using RegEx //
stringToStrip = Regex.Replace(stringToStrip, "(?:\\s*)", "\n\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
stringToStrip = Regex.Replace(stringToStrip, "", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
stringToStrip = Regex.Replace(stringToStrip, "\"", "''", RegexOptions.IgnoreCase | RegexOptions.Compiled);
stringToStrip = StripHtmlXmlTags(stringToStrip);
return stringToStrip;
}
private static string StripHtmlXmlTags(string content)
{
return Regex.Replace(content, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
#region 转化 URL
public static string URLDecode(string text)
{
return HttpUtility.UrlDecode(text, Encoding.Default);
}
public static string URLEncode(string text)
{
return HttpUtility.UrlEncode(text, Encoding.Default);
}
#endregion
///
/// 输入手机号码得到归属地信息
///
/// 手机号码
/// 数组类型0为归属地,1卡类型,2区 号,3邮 编
public static string[] getTelldate(string number)
{
try
{
string strSource = GetUrltoHtml("http://www.ip138.com:8080/search.asp?action=mobile&mobile=" + number.Trim());
//归属地
strSource = strSource.Substring(strSource.IndexOf(number));
strSource = StripHTML(strSource);
strSource = strSource.Replace("\r", "");
strSource = strSource.Replace("\n", "");
strSource = strSource.Replace("\t", "");
strSource = strSource.Replace(" ", "");
strSource = strSource.Replace("-->", "");
string[] strnumber = strSource.Split(new string[] { "归属地", "卡类型", "邮 编", "区 号", "更详细", "卡号" }, StringSplitOptions.RemoveEmptyEntries);
string[] strnumber1 = null;
if (strnumber.Length > 4)
{
strnumber1 = new string[] { strnumber[1].Trim(), strnumber[2].Trim(), strnumber[3].Trim(), strnumber[4].Trim() };
}
return strnumber1;
}
catch (Exception)
{
return null;
}
}
///
/// 请求的公共类用来向服务器发送请求
///
///发送请求的字符串
///返回的是请求的信息
private static string SMSrequest(string strSMSRequest)
{
byte[] data = new byte[1024];
string stringData = null;
IPHostEntry gist = Dns.GetHostByName("www.110.cn");
IPAddress ip = gist.AddressList[0];
//得到IP
IPEndPoint ipEnd = new IPEndPoint(ip, 3121);
//默认80端口号
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//使用tcp协议 stream类型
try
{
socket.Connect(ipEnd);
}
catch (SocketException ex)
{
return "Fail to connect server\r\n" + ex.ToString();
}
string path = strSMSRequest.ToString().Trim();
StringBuilder buf = new StringBuilder();
//buf.Append("GET ").Append(path).Append(" HTTP/1.0\r\n");
//buf.Append("Content-Type: application/x-www-form-urlencoded\r\n");
//buf.Append("\r\n");
byte[] ms = System.Text.UTF8Encoding.UTF8.GetBytes(buf.ToString());
//提交请求的信息
socket.Send(ms);
//接收返回
string strSms = "";
int recv = 0;
do
{
recv = socket.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
//如果请求的页面meta中指定了页面的encoding为gb2312则需要使用对应的Encoding来对字节进行转换()
strSms = strSms + stringData;
//strSms += recv.ToString();
}
while (recv != 0);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
return strSms;
}