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

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

GET 方式:
GET 方式通过在网络地址附加参数来完成数据的提交,比如在地址 http://www.jb51.net/?hl=zh-CN 中,前面部分 http://www.jb51.net表示数据提交的网址,后面部分 hl=zh-CN 表示附加的参数,其中 hl 表示一个键(key), zh-CN 表示这个键对应的值(value)。
程序代码如下:

复制代码代码如下:
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://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 = "http://www.jb51.net/?" + HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}

在上面的程序代码中,我们以 GET 方式访问了网址 http://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( "http://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())
{
   //在这里对接收到的页面内容进行处理
}

在上面的代码中,我们访问了 http://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( "http://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#程序设计有所帮助。

【转】C#中HttpWebRequest的用法详解的更多相关文章

  1. C#中HttpWebRequest的用法详解

    原文链接:http://www.cnblogs.com/love201314/p/5029312.html 1.HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数 ...

  2. C#中HttpWebRequest的用法详解(转载)

    1.HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择.2.命名空间:System.Net3.HttpWebRequest对象不是利用new关键字创建 ...

  3. C#中string.format用法详解

    C#中string.format用法详解 本文实例总结了C#中string.format用法.分享给大家供大家参考.具体分析如下: String.Format 方法的几种定义: String.Form ...

  4. c++中vector的用法详解

    c++中vector的用法详解 vector(向量): C++中的一种数据结构,确切的说是一个类.它相当于一个动态的数组,当程序员无法知道自己需要的数组的规模多大时,用其来解决问题可以达到最大节约空间 ...

  5. php中setcookie函数用法详解(转)

    php中setcookie函数用法详解:        php手册中对setcookie函数讲解的不是很清楚,下面是我做的一些整理,欢迎提出意见.        语法:        bool set ...

  6. JavaScript中return的用法详解

    JavaScript中return的用法详解 最近,跟身边学前端的朋友了解,有很多人对函数中的this的用法和指向问题比较模糊,这里写一篇博客跟大家一起探讨一下this的用法和指向性问题. 1定义 t ...

  7. Mysql中limit的用法详解

    Mysql中limit的用法详解 在我们使用查询语句的时候,经常要返回前几条或者中间某几行数据,为我们提供了limit这样一个功能. SELECT * FROM table LIMIT [offset ...

  8. JavaScript中this的用法详解

    JavaScript中this的用法详解 最近,跟身边学前端的朋友了解,有很多人对函数中的this的用法和指向问题比较模糊,这里写一篇博客跟大家一起探讨一下this的用法和指向性问题. 1定义 thi ...

  9. (转)Shell中read的用法详解

    Shell中read的用法详解 原文:http://blog.csdn.net/jerry_1126/article/details/77406500 read的常用用法如下: read -[pstn ...

随机推荐

  1. Ready事件与Onload事件的区别

    这两种事件都是在页面文档加载时触发的,但Ready比onload先执行. 具体区别如下: 1.在Javascript中,通常使用window.onload方法. window.onload必须等到页面 ...

  2. 简单几何(圆与多边形公共面积) UVALive 7072 Signal Interference (14广州D)

    题目传送门 题意:一个多边形,A点和B点,满足PB <= k * PA的P的范围与多边形的公共面积. 分析:这是个阿波罗尼斯圆.既然是圆,那么设圆的一般方程:(x + D/2) ^ 2 + (y ...

  3. 金子上的友情[XDU1011]

    Problem 1011 - 金子上的友情 Time Limit: 1000MS   Memory Limit: 65536KB   Difficulty: Total Submit: 336  Ac ...

  4. BZOJ1409 : Password

    $f[n]\bmod q=p^{Fib[n]}\bmod q=p^{Fib[n]\bmod\varphi(q)}\bmod q$ 首先线性筛预处理出所有素数,然后对于每次询问,求出$\varphi(q ...

  5. [leetCode][001] Maximum Product Subarray

    题目: Find the contiguous subarray within an array (containing at least one number) which has the larg ...

  6. shell条件与循环

    一.if语句 if [expression] then elif[expression] then else fi 注 : expression前后要有空格:判断相等用 = 而不是 == : then ...

  7. CentoS 下安装gitlab

    curl https://raw.github.com/mattias-ohlsson/gitlab-installer/master/gitlab-install-el6.sh | bash 报错 ...

  8. WritePrivateProfileString()

    在我们写的程序当中,总有一些配置信息需要保存下来,以便完成程序的功能,最简单的办法就是将这些信息写入INI文件中,程序初始化时再读入.具体应用如下: 将信息写入.INI文件中 1.所用的WINAPI函 ...

  9. Disaster recovery best practices for Symantec Endpoint Protection 12.1

    https://support.symantec.com/en_US/article.TECH160736.html

  10. 硬盘参数之TLER

    “你们根本不知道nas盘是用来干啥的,准确的说,要nas盘就是要tler技术,这样才适合用在nas上. TLER=Time-Limited Error Recovery 这么说吧,普通的硬盘(不带TL ...