C#中HttpWebRequest的用法详解
本文实例讲述了C#中HttpWebRequest的用法。分享给大家供大家参考。具体如下:
HttpWebRequest类主要利用HTTP协议和服务器交互,通常是通过GET和POST两种方式来对数据进行获取和提交。下面对这两种方式进行一下说明:
GET方式:
GET方式通过在网络地址附加参数来完成数据的提交,比如在地址https://www.nhooo.com/?hl=zh-CN中,前面部分https://www.nhooo.com表示数据提交的网址,后面部分hl=zh-CN表示附加的参数,其中hl表示一个键(key),zh-CN表示这个键对应的值(value)。
程序代码如下:
HttpWebRequestreq=(HttpWebRequest)HttpWebRequest.Create("https://www.nhooo.com?hl=zh-CN"); req.Method="GET"; using(WebResponsewr=req.GetResponse()) { //在这里对接收到的页面内容进行处理 }
使用GET方式提交中文数据。
GET方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有gb2312和utf8两种。
用gb2312方式编码访问的程序代码如下:
EncodingmyEncoding=Encoding.GetEncoding("gb2312"); stringaddress="https://www.nhooo.com/?"+HttpUtility.UrlEncode("参数一",myEncoding)+"="+HttpUtility.UrlEncode("值一",myEncoding); HttpWebRequestreq=(HttpWebRequest)HttpWebRequest.Create(address); req.Method="GET"; using(WebResponsewr=req.GetResponse()) { //在这里对接收到的页面内容进行处理 }
在上面的程序代码中,我们以GET方式访问了网址https://www.nhooo.com,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。
POST方式:
POST方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和GET方式一样,是类似于hl=zh-CN&newwindow=1这样的结构。
程序代码如下:
stringparam="hl=zh-CN&newwindow=1"; byte[]bs=Encoding.ASCII.GetBytes(param); HttpWebRequestreq=(HttpWebRequest)HttpWebRequest.Create("https://www.nhooo.com/"); 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()) { //在这里对接收到的页面内容进行处理 }
在上面的代码中,我们访问了https://www.nhooo.com的网址,分别以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("https://www.nhooo.com/"); 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; } } }