码迷,mamicode.com
首页 > Web开发 > 详细

HttpWebRequest的使用

时间:2014-11-04 14:49:17      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   http   io   color   ar   os   使用   for   sp   

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

GET 方式

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

程序代码如下:  

C# 代码   复制
bubuko.com,布布扣
  HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.studyofnet.com?hl=zh-CN" );
bubuko.com,布布扣
req.Method = "GET";
bubuko.com,布布扣
using (WebResponse wr = req.GetResponse())
bubuko.com,布布扣
{
bubuko.com,布布扣//在这里对接收到的页面内容进行处理
bubuko.com,布布扣}
bubuko.com,布布扣

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

GET 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种。

用 gb2312 方式编码访问的程序代码如下:

 
C# 代码   复制
bubuko.com,布布扣bubuko.com,布布扣
Encoding myEncoding = Encoding.GetEncoding("gb2312");
bubuko.com,布布扣
string address = "http://www.studyofnet.com/?" + HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding);
bubuko.com,布布扣
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
bubuko.com,布布扣
req.Method = "GET";
bubuko.com,布布扣
using (WebResponse wr = req.GetResponse())
bubuko.com,布布扣
{
bubuko.com,布布扣//在这里对接收到的页面内容进行处理
bubuko.com,布布扣}
bubuko.com,布布扣

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

 

POST 方式

POST 方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和 GET 方式一样,是类似于 hl=zh-CN&newwindow=1 这样的结构。

程序代码如下:

 
C# 代码   复制
bubuko.com,布布扣bubuko.com,布布扣
string param = "hl=zh-CN&newwindow=1";
bubuko.com,布布扣
byte[] bs = Encoding.ASCII.GetBytes(param);
bubuko.com,布布扣bubuko.com,布布扣
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.studyofnet.com/" );
bubuko.com,布布扣
req.Method = "POST";
bubuko.com,布布扣
req.ContentType = "application/x-www-form-urlencoded";
bubuko.com,布布扣
req.ContentLength = bs.Length;
bubuko.com,布布扣bubuko.com,布布扣
using (Stream reqStream = req.GetRequestStream())
bubuko.com,布布扣
{
bubuko.com,布布扣   reqStream.Write(bs, 0, bs.Length);
bubuko.com,布布扣}
bubuko.com,布布扣using (WebResponse wr = req.GetResponse())
bubuko.com,布布扣{
bubuko.com,布布扣   //在这里对接收到的页面内容进行处理
bubuko.com,布布扣} 
bubuko.com,布布扣 
bubuko.com,布布扣

在上面的代码中,我们访问了 http://www.studyofnet.com 的网址,分别以 GET 和 POST 方式提交了数据,并接收了返回的页面内容。然而,如果提交的参数中含有中文,那么这样的处理是不够的,需要对其进行编码,让对方网站能够识别。  

使用 POST 方式提交中文数据

POST 方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。

用 gb2312 方式编码访问的程序代码如下:  

C# 代码   复制
bubuko.com,布布扣
 Encoding myEncoding = Encoding.GetEncoding("gb2312");
bubuko.com,布布扣
string param = HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("参数二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding);
bubuko.com,布布扣bubuko.com,布布扣
byte[] postBytes = Encoding.ASCII.GetBytes(param);
bubuko.com,布布扣bubuko.com,布布扣
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.studyofnet.com/" );
bubuko.com,布布扣
req.Method = "POST";
bubuko.com,布布扣
req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
bubuko.com,布布扣
req.ContentLength = postBytes.Length;
bubuko.com,布布扣bubuko.com,布布扣
using (Stream reqStream = req.GetRequestStream())
bubuko.com,布布扣
{
bubuko.com,布布扣   reqStream.Write(bs, 0, bs.Length);
bubuko.com,布布扣}
bubuko.com,布布扣using (WebResponse wr = req.GetResponse())
bubuko.com,布布扣{
bubuko.com,布布扣   //在这里对接收到的页面内容进行处理
bubuko.com,布布扣} 
bubuko.com,布布扣

从上面的代码可以看出, POST 中文数据的时候,先使用 UrlEncode 方法将中文字符转换为编码后的 ASCII 码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。  

用C#语言写的关于HttpWebRequest 类的使用方法

 
C# 代码   复制
bubuko.com,布布扣bubuko.com,布布扣
using System;
bubuko.com,布布扣
using System.Collections.Generic;
bubuko.com,布布扣
using System.IO;
bubuko.com,布布扣
using System.Net;
bubuko.com,布布扣
using System.Text;
bubuko.com,布布扣bubuko.com,布布扣
namespace HttpWeb
bubuko.com,布布扣
{
bubuko.com,布布扣    /// <summary> 
bubuko.com,布布扣    ///  Http操作类 
bubuko.com,布布扣    /// </summary> 
bubuko.com,布布扣    public static class httptest
bubuko.com,布布扣    {
bubuko.com,布布扣        /// <summary> 
bubuko.com,布布扣        ///  获取网址HTML 
bubuko.com,布布扣        /// </summary> 
bubuko.com,布布扣        /// <param name="URL">网址 </param> 
bubuko.com,布布扣        /// <returns> </returns> 
bubuko.com,布布扣        public static string GetHtml(string URL)
bubuko.com,布布扣        {
bubuko.com,布布扣            WebRequest wrt;
bubuko.com,布布扣            wrt = WebRequest.Create(URL);
bubuko.com,布布扣            wrt.Credentials = CredentialCache.DefaultCredentials;
bubuko.com,布布扣            WebResponse wrp;
bubuko.com,布布扣            wrp = wrt.GetResponse();
bubuko.com,布布扣            string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();
bubuko.com,布布扣            try
bubuko.com,布布扣            {
bubuko.com,布布扣                wrt.GetResponse().Close();
bubuko.com,布布扣            }
bubuko.com,布布扣            catch (WebException ex)
bubuko.com,布布扣            {
bubuko.com,布布扣                throw ex;
bubuko.com,布布扣            }
bubuko.com,布布扣            return reader;
bubuko.com,布布扣        }
bubuko.com,布布扣        /// <summary> 
bubuko.com,布布扣        /// 获取网站cookie 
bubuko.com,布布扣        /// </summary> 
bubuko.com,布布扣        /// <param name="URL">网址 </param> 
bubuko.com,布布扣        /// <param name="cookie">cookie </param> 
bubuko.com,布布扣        /// <returns> </returns> 
bubuko.com,布布扣        public static string GetHtml(string URL, out string cookie)
bubuko.com,布布扣        {
bubuko.com,布布扣            WebRequest wrt;
bubuko.com,布布扣            wrt = WebRequest.Create(URL);
bubuko.com,布布扣            wrt.Credentials = CredentialCache.DefaultCredentials;
bubuko.com,布布扣            WebResponse wrp;
bubuko.com,布布扣
bubuko.com,布布扣            wrp = wrt.GetResponse();
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣            string html = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();
bubuko.com,布布扣
bubuko.com,布布扣            try
bubuko.com,布布扣            {
bubuko.com,布布扣                wrt.GetResponse().Close();
bubuko.com,布布扣            }
bubuko.com,布布扣            catch (WebException ex)
bubuko.com,布布扣            {
bubuko.com,布布扣                throw ex;
bubuko.com,布布扣            }
bubuko.com,布布扣
bubuko.com,布布扣            cookie = wrp.Headers.Get("Set-Cookie");
bubuko.com,布布扣            return html;
bubuko.com,布布扣        }
bubuko.com,布布扣        public static string GetHtml(string URL, string postData, string cookie, out string header, string server)
bubuko.com,布布扣        {
bubuko.com,布布扣            return GetHtml(server, URL, postData, cookie, out header);
bubuko.com,布布扣        }
bubuko.com,布布扣        public static string GetHtml(string server, string URL, string postData, string cookie, out string header)
bubuko.com,布布扣        {
bubuko.com,布布扣            byte[] byteRequest = Encoding.GetEncoding("gb2312").GetBytes(postData);
bubuko.com,布布扣            return GetHtml(server, URL, byteRequest, cookie, out header);
bubuko.com,布布扣        }
bubuko.com,布布扣        public static string GetHtml(string server, string URL, byte[] byteRequest, string cookie, out string header)
bubuko.com,布布扣        {
bubuko.com,布布扣            byte[] bytes = GetHtmlByBytes(server, URL, byteRequest, cookie, out header);
bubuko.com,布布扣            Stream getStream = new MemoryStream(bytes);
bubuko.com,布布扣            StreamReader streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));
bubuko.com,布布扣            string getString = streamReader.ReadToEnd();
bubuko.com,布布扣            streamReader.Close();
bubuko.com,布布扣            getStream.Close();
bubuko.com,布布扣            return getString;
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        /// <summary> 
bubuko.com,布布扣        /// Post模式浏览 
bubuko.com,布布扣        /// </summary> 
bubuko.com,布布扣        /// <param name="server">服务器地址 </param> 
bubuko.com,布布扣        /// <param name="URL">网址 </param> 
bubuko.com,布布扣        /// <param name="byteRequest">流 </param> 
bubuko.com,布布扣        /// <param name="cookie">cookie </param> 
bubuko.com,布布扣        /// <param name="header">句柄 </param> 
bubuko.com,布布扣        /// <returns> </returns> 
bubuko.com,布布扣        public static byte[] GetHtmlByBytes(string server, string URL, byte[] byteRequest, string cookie, out string header)
bubuko.com,布布扣        {
bubuko.com,布布扣            long contentLength;
bubuko.com,布布扣            HttpWebRequest httpWebRequest;
bubuko.com,布布扣            HttpWebResponse webResponse;
bubuko.com,布布扣            Stream getStream;
bubuko.com,布布扣
bubuko.com,布布扣            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
bubuko.com,布布扣            CookieContainer co = new CookieContainer();
bubuko.com,布布扣            co.SetCookies(new Uri(server), cookie);
bubuko.com,布布扣
bubuko.com,布布扣            httpWebRequest.CookieContainer = co;
bubuko.com,布布扣
bubuko.com,布布扣            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
bubuko.com,布布扣            httpWebRequest.Accept =
bubuko.com,布布扣                "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
bubuko.com,布布扣            httpWebRequest.Referer = server;
bubuko.com,布布扣            httpWebRequest.UserAgent =
bubuko.com,布布扣                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
bubuko.com,布布扣            httpWebRequest.Method = "Post";
bubuko.com,布布扣            httpWebRequest.ContentLength = byteRequest.Length;
bubuko.com,布布扣            Stream stream;
bubuko.com,布布扣            stream = httpWebRequest.GetRequestStream();
bubuko.com,布布扣            stream.Write(byteRequest, 0, byteRequest.Length);
bubuko.com,布布扣            stream.Close();
bubuko.com,布布扣            webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
bubuko.com,布布扣            header = webResponse.Headers.ToString();
bubuko.com,布布扣            getStream = webResponse.GetResponseStream();
bubuko.com,布布扣            contentLength = webResponse.ContentLength;
bubuko.com,布布扣
bubuko.com,布布扣            byte[] outBytes = new byte[contentLength];
bubuko.com,布布扣            outBytes = ReadFully(getStream);
bubuko.com,布布扣            getStream.Close();
bubuko.com,布布扣            return outBytes;
bubuko.com,布布扣        }
bubuko.com,布布扣        public static byte[] ReadFully(Stream stream)
bubuko.com,布布扣        {
bubuko.com,布布扣            byte[] buffer = new byte[128];
bubuko.com,布布扣            using (MemoryStream ms = new MemoryStream())
bubuko.com,布布扣            {
bubuko.com,布布扣                while (true)
bubuko.com,布布扣                {
bubuko.com,布布扣                    int read = stream.Read(buffer, 0, buffer.Length);
bubuko.com,布布扣                    if (read <= 0)
bubuko.com,布布扣                        return ms.ToArray();
bubuko.com,布布扣                    ms.Write(buffer, 0, read);
bubuko.com,布布扣                }
bubuko.com,布布扣            }
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        /// <summary> 
bubuko.com,布布扣        /// Get模式 
bubuko.com,布布扣        /// </summary> 
bubuko.com,布布扣        /// <param name="URL">网址 </param> 
bubuko.com,布布扣        /// <param name="cookie">cookies </param> 
bubuko.com,布布扣        /// <param name="header">句柄 </param> 
bubuko.com,布布扣        /// <param name="server">服务器 </param> 
bubuko.com,布布扣        /// <param name="val">服务器 </param> 
bubuko.com,布布扣        /// <returns> </returns> 
bubuko.com,布布扣        public static string GetHtml(string URL, string cookie, out string header, string server)
bubuko.com,布布扣        {
bubuko.com,布布扣            return GetHtml(URL, cookie, out header, server, "");
bubuko.com,布布扣        }
bubuko.com,布布扣        /// <summary> 
bubuko.com,布布扣        /// Get模式浏览 
bubuko.com,布布扣        /// </summary> 
bubuko.com,布布扣        /// <param name="URL">Get网址 </param> 
bubuko.com,布布扣        /// <param name="cookie">cookie </param> 
bubuko.com,布布扣        /// <param name="header">句柄 </param> 
bubuko.com,布布扣        /// <param name="server">服务器地址 </param> 
bubuko.com,布布扣        /// <param name="val"> </param> 
bubuko.com,布布扣        /// <returns> </returns> 
bubuko.com,布布扣        public static string GetHtml(string URL, string cookie, out string header, string server, string val)
bubuko.com,布布扣        {
bubuko.com,布布扣            HttpWebRequest httpWebRequest;
bubuko.com,布布扣            HttpWebResponse webResponse;
bubuko.com,布布扣            Stream getStream;
bubuko.com,布布扣            StreamReader streamReader;
bubuko.com,布布扣            string getString = "";
bubuko.com,布布扣            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
bubuko.com,布布扣            httpWebRequest.Accept = "*/*";
bubuko.com,布布扣            httpWebRequest.Referer = server;
bubuko.com,布布扣            CookieContainer co = new CookieContainer();
bubuko.com,布布扣            co.SetCookies(new Uri(server), cookie);
bubuko.com,布布扣            httpWebRequest.CookieContainer = co;
bubuko.com,布布扣            httpWebRequest.UserAgent =
bubuko.com,布布扣                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
bubuko.com,布布扣            httpWebRequest.Method = "GET";
bubuko.com,布布扣            webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
bubuko.com,布布扣            header = webResponse.Headers.ToString();
bubuko.com,布布扣            getStream = webResponse.GetResponseStream();
bubuko.com,布布扣            streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));
bubuko.com,布布扣            getString = streamReader.ReadToEnd();
bubuko.com,布布扣
bubuko.com,布布扣            streamReader.Close();
bubuko.com,布布扣            getStream.Close();
bubuko.com,布布扣            return getString;
bubuko.com,布布扣        }
bubuko.com,布布扣   }
bubuko.com,布布扣}
bubuko.com,布布扣

 

HttpWebRequest的使用

标签:style   http   io   color   ar   os   使用   for   sp   

原文地址:http://www.cnblogs.com/gc2013/p/4073540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!