Csharp/C#教程:C#中HttpWebRequest的用法详解分享

本文实例讲述了C#中HttpWebRequest的用法。分享给大家供大家参考。具体如下:

HttpWebRequest类主要利用HTTP协议和服务器交互,通常是通过GET和POST两种方式来对数据进行获取和提交。下面对这两种方式进行一下说明:

GET方式:
GET方式通过在网络地址附加参数来完成数据的提交,比如在地址//www.jb51.net/?hl=zh-CN中,前面部分//www.jb51.net表示数据提交的网址,后面部分hl=zh-CN表示附加的参数,其中hl表示一个键(key),zh-CN表示这个键对应的值(value)。
程序代码如下: 
代码如下:HttpWebRequestreq=(HttpWebRequest)HttpWebRequest.Create(“//www.jb51.net?hl=zh-CN”);
req.Method=”GET”;
using(WebResponsewr=req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}

使用GET方式提交中文数据。

GET方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有gb2312和utf8两种。
用gb2312方式编码访问的程序代码如下:
代码如下:EncodingmyEncoding=Encoding.GetEncoding(“gb2312”);
stringaddress=”//www.jb51.net/?”+HttpUtility.UrlEncode(“参数一”,myEncoding)+”=”+HttpUtility.UrlEncode(“值一”,myEncoding);
HttpWebRequestreq=(HttpWebRequest)HttpWebRequest.Create(address);
req.Method=”GET”;
using(WebResponsewr=req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
在上面的程序代码中,我们以GET方式访问了网址//www.jb51.net,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。
 
POST方式:

POST方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和GET方式一样,是类似于hl=zh-CN&newwindow=1这样的结构。
程序代码如下:
代码如下:stringparam=”hl=zh-CN&newwindow=1″;
byte[]bs=Encoding.ASCII.GetBytes(param);
HttpWebRequestreq=(HttpWebRequest)HttpWebRequest.Create(“//www.jb51.net/”);
req.Method=”POST”;
req.ContentType=”application/x-www-form-urlencoded”;
req.ContentLength=bs.Length;
using(StreamreqStream=req.GetRequestStream())
{
  reqStream.Write(bs,0,bs.Length);
}
using(WebResponsewr=req.GetResponse())
{
  //在这里对接收到的页面内容进行处理
}

在上面的代码中,我们访问了//www.jb51.net的网址,分别以GET和POST方式提交了数据,并接收了返回的页面内容。然而,如果提交的参数中含有中文,那么这样的处理是不够的,需要对其进行编码,让对方网站能够识别。 
使用POST方式提交中文数据
POST方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。
用gb2312方式编码访问的程序代码如下: 
代码如下:EncodingmyEncoding=Encoding.GetEncoding(“gb2312”);
stringparam=HttpUtility.UrlEncode(“参数一”,myEncoding)+”=”+HttpUtility.UrlEncode(“值一”,myEncoding)+”&”+HttpUtility.UrlEncode(“参数二”,myEncoding)+”=”+HttpUtility.UrlEncode(“值二”,myEncoding);
byte[]postBytes=Encoding.ASCII.GetBytes(param);
HttpWebRequestreq=(HttpWebRequest)HttpWebRequest.Create(“//www.jb51.net/”);
req.Method=”POST”;
req.ContentType=”application/x-www-form-urlencoded;charset=gb2312″;
req.ContentLength=postBytes.Length;
using(StreamreqStream=req.GetRequestStream())
{
  reqStream.Write(bs,0,bs.Length);
}
using(WebResponsewr=req.GetResponse())
{
  //在这里对接收到的页面内容进行处理
}
从上面的代码可以看出,POST中文数据的时候,先使用UrlEncode方法将中文字符转换为编码后的ASCII码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。 
用C#语言写的关于HttpWebRequest类的使用方法
代码如下:usingSystem;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Net;
usingSystem.Text;
namespaceHttpWeb
{
   ///<summary>
   /// Http操作类
   ///</summary>
   publicstaticclasshttptest
   {
       ///<summary>
       /// 获取网址HTML
       ///</summary>
       ///<paramname=”URL”>网址</param>
       ///<returns></returns>
       publicstaticstringGetHtml(stringURL)
       {
           WebRequestwrt;
           wrt=WebRequest.Create(URL);
           wrt.Credentials=CredentialCache.DefaultCredentials;
           WebResponsewrp;
           wrp=wrt.GetResponse();
           stringreader=newStreamReader(wrp.GetResponseStream(),Encoding.GetEncoding(“gb2312”)).ReadToEnd();
           try
           {
               wrt.GetResponse().Close();
           }
           catch(WebExceptionex)
           {
               throwex;
           }
           returnreader;
       }
       ///<summary>
       ///获取网站cookie
       ///</summary>
       ///<paramname=”URL”>网址</param>
       ///<paramname=”cookie”>cookie</param>
       ///<returns></returns>
       publicstaticstringGetHtml(stringURL,outstringcookie)
       {
           WebRequestwrt;
           wrt=WebRequest.Create(URL);
           wrt.Credentials=CredentialCache.DefaultCredentials;
           WebResponsewrp;
           wrp=wrt.GetResponse();

           stringhtml=newStreamReader(wrp.GetResponseStream(),Encoding.GetEncoding(“gb2312”)).ReadToEnd();
           try
           {
               wrt.GetResponse().Close();
           }
           catch(WebExceptionex)
           {
               throwex;
           }
           cookie=wrp.Headers.Get(“Set-Cookie”);
           returnhtml;
       }
       publicstaticstringGetHtml(stringURL,stringpostData,stringcookie,outstringheader,stringserver)
       {
           returnGetHtml(server,URL,postData,cookie,outheader);
       }
       publicstaticstringGetHtml(stringserver,stringURL,stringpostData,stringcookie,outstringheader)
       {
           byte[]byteRequest=Encoding.GetEncoding(“gb2312”).GetBytes(postData);
           returnGetHtml(server,URL,byteRequest,cookie,outheader);
       }
       publicstaticstringGetHtml(stringserver,stringURL,byte[]byteRequest,stringcookie,outstringheader)
       {
           byte[]bytes=GetHtmlByBytes(server,URL,byteRequest,cookie,outheader);
           StreamgetStream=newMemoryStream(bytes);
           StreamReaderstreamReader=newStreamReader(getStream,Encoding.GetEncoding(“gb2312”));
           stringgetString=streamReader.ReadToEnd();
           streamReader.Close();
           getStream.Close();
           returngetString;
       }
       ///<summary>
       ///Post模式浏览
       ///</summary>
       ///<paramname=”server”>服务器地址</param>
       ///<paramname=”URL”>网址</param>
       ///<paramname=”byteRequest”>流</param>
       ///<paramname=”cookie”>cookie</param>
       ///<paramname=”header”>句柄</param>
       ///<returns></returns>
       publicstaticbyte[]GetHtmlByBytes(stringserver,stringURL,byte[]byteRequest,stringcookie,outstringheader)
       {
           longcontentLength;
           HttpWebRequesthttpWebRequest;
           HttpWebResponsewebResponse;
           StreamgetStream;
           httpWebRequest=(HttpWebRequest)HttpWebRequest.Create(URL);
           CookieContainerco=newCookieContainer();
           co.SetCookies(newUri(server),cookie);
           httpWebRequest.CookieContainer=co;
           httpWebRequest.ContentType=”application/x-www-form-urlencoded”;
           httpWebRequest.Accept=
               “image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/x-shockwave-flash,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*”;
           httpWebRequest.Referer=server;
           httpWebRequest.UserAgent=
               “Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1;Maxthon;.NETCLR1.1.4322)”;
           httpWebRequest.Method=”Post”;
           httpWebRequest.ContentLength=byteRequest.Length;
           Streamstream;
           stream=httpWebRequest.GetRequestStream();
           stream.Write(byteRequest,0,byteRequest.Length);
           stream.Close();
           webResponse=(HttpWebResponse)httpWebRequest.GetResponse();
           header=webResponse.Headers.ToString();
           getStream=webResponse.GetResponseStream();
           contentLength=webResponse.ContentLength;
           byte[]outBytes=newbyte[contentLength];
           outBytes=ReadFully(getStream);
           getStream.Close();
           returnoutBytes;
       }
       publicstaticbyte[]ReadFully(Streamstream)
       {
           byte[]buffer=newbyte[128];
           using(MemoryStreamms=newMemoryStream())
           {
               while(true)
               {
                   intread=stream.Read(buffer,0,buffer.Length);
                   if(read<=0)
                       returnms.ToArray();
                   ms.Write(buffer,0,read);
               }
           }
       }
       ///<summary>
       ///Get模式
       ///</summary>
       ///<paramname=”URL”>网址</param>
       ///<paramname=”cookie”>cookies</param>
       ///<paramname=”header”>句柄</param>
       ///<paramname=”server”>服务器</param>
       ///<paramname=”val”>服务器</param>
       ///<returns></returns>
       publicstaticstringGetHtml(stringURL,stringcookie,outstringheader,stringserver)
       {
           returnGetHtml(URL,cookie,outheader,server,””);
       }
       ///<summary>
       ///Get模式浏览
       ///</summary>
       ///<paramname=”URL”>Get网址</param>
       ///<paramname=”cookie”>cookie</param>
       ///<paramname=”header”>句柄</param>
       ///<paramname=”server”>服务器地址</param>
       ///<paramname=”val”></param>
       ///<returns></returns>
       publicstaticstringGetHtml(stringURL,stringcookie,outstringheader,stringserver,stringval)
       {
           HttpWebRequesthttpWebRequest;
           HttpWebResponsewebResponse;
           StreamgetStream;
           StreamReaderstreamReader;
           stringgetString=””;
           httpWebRequest=(HttpWebRequest)HttpWebRequest.Create(URL);
           httpWebRequest.Accept=”*/*”;
           httpWebRequest.Referer=server;
           CookieContainerco=newCookieContainer();
           co.SetCookies(newUri(server),cookie);
           httpWebRequest.CookieContainer=co;
           httpWebRequest.UserAgent=
               “Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1;Maxthon;.NETCLR1.1.4322)”;
           httpWebRequest.Method=”GET”;
           webResponse=(HttpWebResponse)httpWebRequest.GetResponse();
           header=webResponse.Headers.ToString();
           getStream=webResponse.GetResponseStream();
           streamReader=newStreamReader(getStream,Encoding.GetEncoding(“gb2312”));
           getString=streamReader.ReadToEnd();
           streamReader.Close();
           getStream.Close();
           returngetString;
       }
  }
}

希望本文所述对大家的C#程序设计有所帮助。

您可能感兴趣的文章:C#基于HttpWebRequest实现发送HTTP请求的方法分析C#使用HttpWebRequest与HttpWebResponse模拟用户登录C#httpwebrequest访问HTTPS错误处理方法浅谈C#中HttpWebRequest与HttpWebResponse的使用方法C#采用HttpWebRequest实现保持会话上传文件到HTTP的方法c#HttpWebRequest通过代理服务器抓取网页内容应用介绍C#使用HttpWebRequest重定向方法详解

标签: ue st

C语言解字符串逆序和单向链表逆序问题的代码示例

C语言判断一个数是否是2的幂次方或4的幂次方

上述就是C#学习教程:C#中HttpWebRequest的用法详解分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/905873.html

(0)
上一篇 2021年10月23日
下一篇 2021年10月23日

精彩推荐