当前位置: 移动技术网 > IT编程>开发语言>c# > 浅谈C#中HttpWebRequest与HttpWebResponse的使用方法

浅谈C#中HttpWebRequest与HttpWebResponse的使用方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

这个类是专门为http的get和post请求写的,解决了编码,证书,自动带cookie等问题。

c# httphelper,帮助类,真正的httprequest请求时无视编码,无视证书,无视cookie,网页抓取

1.第一招,根据url地址获取网页信息

先来看一下代码

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 "";
}

post方法

///<summary>
///采用https协议访问网络
///</summary>
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();
  }
}

这招是入门第一式, 特点:

1.最简单最直观的一种,入门课程。

2.适应于明文,无需登录,无需任何验证就可以进入的页面。

3.获取的数据类型为html文档。

4.请求方法为get/post

2.第二招,根据url地址获取需要验证证书才能访问的网页信息

先来看一下代码

get方法

 //回调验证证书问题
public bool checkvalidationresult(object sender, x509certificate certificate, x509chain chain, sslpolicyerrors errors)
{ 
 // 总是接受 
 return true;
}
/// <summary>
/// 传入url返回网页的html代码
/// </summary>
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();
}

post方法

//回调验证证书问题
public bool checkvalidationresult(object sender, x509certificate certificate, x509chain chain, sslpolicyerrors errors)
{
 // 总是接受 
 return true;
}
///<summary>
///采用https协议访问网络
///</summary>
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();
  }
}

这招是学会算是进了大门了,凡是需要验证证书才能进入的页面都可以使用这个方法进入,我使用的是证书回调验证的方式,证书验证是否通过在客户端验证,这样的话我们就可以使用自己定义一个方法来验证了,有的人会说那也不清楚是怎么样验证的啊,其它很简单,代码是自己写的为什么要那么难为自己呢,直接返回一个true不就完了,永远都是验证通过,这样就可以无视证书的存在了, 特点:

1.入门前的小难题,初级课程。

2.适应于无需登录,明文但需要验证证书才能访问的页面。

3.获取的数据类型为html文档。

4.请求方法为get/post

3.第三招,根据url地址获取需要登录才能访问的网页信息

我们先来分析一下这种类型的网页,需要登录才能访问的网页,其它呢也是一种验证,验证什么呢,验证客户端是否登录,是否具用相应的凭证,需要登录的都要验证sessionid这是每一个需要登录的页面都需要验证的,那我们怎么做的,我们第一步就是要得存在cookie里面的数据包括sessionid,那怎么得到呢,这个方法很多,使用id9或者是火狐浏览器很容易就能得到。

提供一个网页抓取hao123手机号码归属地的例子  这里面针对id9有详细的说明。

如果我们得到了登录的cookie信息之后那个再去访问相应的页面就会非常的简单了,其它说白了就是把本地的cookie信息在请求的时候捎带过去就行了。

看代码

get方法

/// <summary>
/// 传入url返回网页的html代码带有证书的方法
/// </summary>
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://txw1958.cnblogs.com";
  cookiecontainer objcok = new cookiecontainer();
  objcok.add(new uri("http://txw1958.cnblogs.com"), new cookie("键", "值"));
  objcok.add(new uri("http://txw1958.cnblogs.com"), new cookie("键", "值"));
  objcok.add(new uri("http://txw1958.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();
}

post方法。

///<summary>
///采用https协议访问网络
///</summary>
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://txw1958.cnblogs.com"), new cookie("键", "值"));
 objcok.add(new uri("http://txw1958.cnblogs.com"), new cookie("键", "值"));
 objcok.add(new uri("http://txw1958.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();
}

特点:

1.还算有点水类型的,练习成功后可以小牛一把。

2.适应于需要登录才能访问的页面。

3.获取的数据类型为html文档。

4.请求方法为get/post

总结一下,其它基本的技能就这几个部分,如果再深入的话那就是基本技能的组合了

比如,

1. 先用get或者post方法登录然后取得cookie再去访问页面得到信息,这种其它也是上面技能的组合,这里需要以请求后做这样一步。response.cookie

这就是在你请求后可以得到当次cookie的方法,直接取得返回给上一个方法使用就行了,上面我们都是自己构造的,在这里直接使用这个cookie就可以了。

2.如果我们碰到需要登录而且还要验证证书的网页怎么办,其它这个也很简单把我们上面的方法综合 一下就行了,如下代码这里我以get为例子post例子也是同样的方法

/// <summary>
/// 传入url返回网页的html代码
/// </summary>
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();
}

3.如果我们碰到那种需要验证网页来源的方法应该怎么办呢,这种情况其它是有些程序员会想到你可能会使用程序,自动来获取网页信息,为了防止就使用页面来源来验证,就是说只要不是从他们所在页面或是域名过来的请求就不接受,有的是直接验证来源的ip,这些都可以使用下面一句来进入,这主要是这个地址是可以直接伪造的

request.referer = <a href=//www.jb51.net>//www.jb51.net</a>;

呵呵其它很简单因为这个地址可以直接修改。但是如果服务器上验证的是来源的url那就完了,我们就得去修改数据包了,这个有点难度暂时不讨论。

4.提供一些与这个例子相配置的方法

过滤html标签的方法

/// <summary>
/// 过滤html标签
/// </summary>
public static string striphtml(string stringtostrip)
{
 // paring using regex   //
 stringtostrip = regex.replace(stringtostrip, "</p(?:\\s*)>(?:\\s*)<p(?:\\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);
}

url转化的方法

#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

提供一个实际例子,这个是使用ip138来查询手机号码归属地的方法,其它在我的上一次文章里都有,在这里我再放上来是方便大家阅读,这方面的技术其它研究起来很有意思,希望大家多提建议,我相信应该还有更多更好,更完善的方法,在这里给大家提供一个参考吧。感谢支持

上例子

/// <summary>
/// 输入手机号码得到归属地信息
/// </summary>
/// <returns>数组类型0为归属地,1卡类型,2区 号,3邮 编</returns>
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;
 }
}

这个例子写是不怎么样,些地方是可以简化的,这个接口而且可以直接使用xml得到,但我在这里的重点是让一些新手看看方法和思路风凉啊,呵呵

第四招,通过socket访问

///<summary>
/// 请求的公共类用来向服务器发送请求
///</summary>
///<param name="strsmsrequest">发送请求的字符串</param>
///<returns>返回的是请求的信息</returns>
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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网