欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中HttpWebRequest的用法详解

程序员文章站 2023-12-17 13:46:58
本文实例讲述了c#中httpwebrequest的用法。分享给大家供大家参考。具体如下: httpwebrequest类主要利用http 协议和服务器交互,通常是通过 g...

本文实例讲述了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)。
程序代码如下: 

复制代码 代码如下:
httpwebrequest req = (httpwebrequest) httpwebrequest.create( "//www.jb51.net?hl=zh-cn" );
req.method = "get";
using (webresponse wr = req.getresponse())
{
//在这里对接收到的页面内容进行处理
}

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

get 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种。
用 gb2312 方式编码访问的程序代码如下:

复制代码 代码如下:
encoding myencoding = encoding.getencoding("gb2312");
string address = "//www.jb51.net/?" + httputility.urlencode("参数一", myencoding) + "=" + httputility.urlencode("值一", myencoding);
httpwebrequest req = (httpwebrequest)httpwebrequest.create(address);
req.method = "get";
using (webresponse wr = req.getresponse())
{
//在这里对接收到的页面内容进行处理
}

在上面的程序代码中,我们以 get 方式访问了网址 //www.jb51.net ,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。
 
post 方式:

post 方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和 get 方式一样,是类似于 hl=zh-cn&newwindow=1 这样的结构。
程序代码如下:

复制代码 代码如下:
string param = "hl=zh-cn&newwindow=1";
byte[] bs = encoding.ascii.getbytes(param);
httpwebrequest req = (httpwebrequest) httpwebrequest.create( "//www.jb51.net/" );
req.method = "post";
req.contenttype = "application/x-www-form-urlencoded";
req.contentlength = bs.length;
using (stream reqstream = req.getrequeststream())
{
   reqstream.write(bs, 0, bs.length);
}
using (webresponse wr = req.getresponse())
{
   //在这里对接收到的页面内容进行处理
}

在上面的代码中,我们访问了 //www.jb51.net 的网址,分别以 get 和 post 方式提交了数据,并接收了返回的页面内容。然而,如果提交的参数中含有中文,那么这样的处理是不够的,需要对其进行编码,让对方网站能够识别。 
使用 post 方式提交中文数据
post 方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。
用 gb2312 方式编码访问的程序代码如下: 

复制代码 代码如下:
encoding myencoding = encoding.getencoding("gb2312");
string param = httputility.urlencode("参数一", myencoding) + "=" + httputility.urlencode("值一", myencoding) + "&" + httputility.urlencode("参数二", myencoding) + "=" + httputility.urlencode("值二", myencoding);
byte[] postbytes = encoding.ascii.getbytes(param);
httpwebrequest req = (httpwebrequest) httpwebrequest.create( "//www.jb51.net/" );
req.method = "post";
req.contenttype = "application/x-www-form-urlencoded;charset=gb2312";
req.contentlength = postbytes.length;
using (stream reqstream = req.getrequeststream())
{
   reqstream.write(bs, 0, bs.length);
}
using (webresponse wr = req.getresponse())
{
   //在这里对接收到的页面内容进行处理
}

从上面的代码可以看出, post 中文数据的时候,先使用 urlencode 方法将中文字符转换为编码后的 ascii 码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。 
用c#语言写的关于httpwebrequest 类的使用方法
复制代码 代码如下:
using system;
using system.collections.generic;
using system.io;
using system.net;
using system.text;
namespace httpweb
{
    /// <summary>
    ///  http操作类
    /// </summary>
    public static class httptest
    {
        /// <summary>
        ///  获取网址html
        /// </summary>
        /// <param name="url">网址 </param>
        /// <returns> </returns>
        public static string gethtml(string url)
        {
            webrequest wrt;
            wrt = webrequest.create(url);
            wrt.credentials = credentialcache.defaultcredentials;
            webresponse wrp;
            wrp = wrt.getresponse();
            string reader = new streamreader(wrp.getresponsestream(), encoding.getencoding("gb2312")).readtoend();
            try
            {
                wrt.getresponse().close();
            }
            catch (webexception ex)
            {
                throw ex;
            }
            return reader;
        }
        /// <summary>
        /// 获取网站cookie
        /// </summary>
        /// <param name="url">网址 </param>
        /// <param name="cookie">cookie </param>
        /// <returns> </returns>
        public static string gethtml(string url, out string cookie)
        {
            webrequest wrt;
            wrt = webrequest.create(url);
            wrt.credentials = credentialcache.defaultcredentials;
            webresponse wrp;
            wrp = wrt.getresponse();

            string html = new streamreader(wrp.getresponsestream(), encoding.getencoding("gb2312")).readtoend();
            try
            {
                wrt.getresponse().close();
            }
            catch (webexception ex)
            {
                throw ex;
            }
            cookie = wrp.headers.get("set-cookie");
            return html;
        }
        public static string gethtml(string url, string postdata, string cookie, out string header, string server)
        {
            return gethtml(server, url, postdata, cookie, out header);
        }
        public static string gethtml(string server, string url, string postdata, string cookie, out string header)
        {
            byte[] byterequest = encoding.getencoding("gb2312").getbytes(postdata);
            return gethtml(server, url, byterequest, cookie, out header);
        }
        public static string gethtml(string server, string url, byte[] byterequest, string cookie, out string header)
        {
            byte[] bytes = gethtmlbybytes(server, url, byterequest, cookie, out header);
            stream getstream = new memorystream(bytes);
            streamreader streamreader = new streamreader(getstream, encoding.getencoding("gb2312"));
            string getstring = streamreader.readtoend();
            streamreader.close();
            getstream.close();
            return getstring;
        }
        /// <summary>
        /// post模式浏览
        /// </summary>
        /// <param name="server">服务器地址 </param>
        /// <param name="url">网址 </param>
        /// <param name="byterequest">流 </param>
        /// <param name="cookie">cookie </param>
        /// <param name="header">句柄 </param>
        /// <returns> </returns>
        public static byte[] gethtmlbybytes(string server, string url, byte[] byterequest, string cookie, out string header)
        {
            long contentlength;
            httpwebrequest httpwebrequest;
            httpwebresponse webresponse;
            stream getstream;
            httpwebrequest = (httpwebrequest)httpwebrequest.create(url);
            cookiecontainer co = new cookiecontainer();
            co.setcookies(new uri(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; msie 6.0; windows nt 5.1; sv1; maxthon; .net clr 1.1.4322)";
            httpwebrequest.method = "post";
            httpwebrequest.contentlength = byterequest.length;
            stream stream;
            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 = new byte[contentlength];
            outbytes = readfully(getstream);
            getstream.close();
            return outbytes;
        }
        public static byte[] readfully(stream stream)
        {
            byte[] buffer = new byte[128];
            using (memorystream ms = new memorystream())
            {
                while (true)
                {
                    int read = stream.read(buffer, 0, buffer.length);
                    if (read <= 0)
                        return ms.toarray();
                    ms.write(buffer, 0, read);
                }
            }
        }
        /// <summary>
        /// get模式
        /// </summary>
        /// <param name="url">网址 </param>
        /// <param name="cookie">cookies </param>
        /// <param name="header">句柄 </param>
        /// <param name="server">服务器 </param>
        /// <param name="val">服务器 </param>
        /// <returns> </returns>
        public static string gethtml(string url, string cookie, out string header, string server)
        {
            return gethtml(url, cookie, out header, server, "");
        }
        /// <summary>
        /// get模式浏览
        /// </summary>
        /// <param name="url">get网址 </param>
        /// <param name="cookie">cookie </param>
        /// <param name="header">句柄 </param>
        /// <param name="server">服务器地址 </param>
        /// <param name="val"> </param>
        /// <returns> </returns>
        public static string gethtml(string url, string cookie, out string header, string server, string val)
        {
            httpwebrequest httpwebrequest;
            httpwebresponse webresponse;
            stream getstream;
            streamreader streamreader;
            string getstring = "";
            httpwebrequest = (httpwebrequest)httpwebrequest.create(url);
            httpwebrequest.accept = "*/*";
            httpwebrequest.referer = server;
            cookiecontainer co = new cookiecontainer();
            co.setcookies(new uri(server), cookie);
            httpwebrequest.cookiecontainer = co;
            httpwebrequest.useragent =
                "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1; sv1; maxthon; .net clr 1.1.4322)";
            httpwebrequest.method = "get";
            webresponse = (httpwebresponse)httpwebrequest.getresponse();
            header = webresponse.headers.tostring();
            getstream = webresponse.getresponsestream();
            streamreader = new streamreader(getstream, encoding.getencoding("gb2312"));
            getstring = streamreader.readtoend();
            streamreader.close();
            getstream.close();
            return getstring;
        }
   }
}

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

上一篇:

下一篇: