使用 HttpWebRequest 发送模拟 POST 请求

使用HttpWebRequest发送模拟POST请求

 

 网页中,如果form的method="POST",这时点击submit按钮可以给服务器发送了一个POST请求,如果method="GET",就是向服务器发送GET请求.
有兴趣可以先看看POST和GET的区别和使用方法。
 

这里,我在ASP.NET中使用两个简单的示例介绍了HttpWebRequest对像和使用HttpWebRequest对像模拟POST请求,HttpWebRequest对HTTP协议进行了完整的封装,对HTTP协议中的Header, Content, Cookie 都做了属性和方法的支持,很容易就能编写出一个模拟浏览器自动登录的程序。

 MSDN对HttpWebRequestHttpWebResponse的说明:

 这里简要介绍如何使用

HttpWebRequest&HttpWebResponse两个对象与HTTP服务器进行直接交互的过程,

HttpWebRequest类对WebRequest中定义的属性和方法提供支持,在使用HttpWebRequest对象向HTTP服务器发起请求时请不要使用HttpWebRequest对象的构造函数,而应该使用WebRequest.Create()方法来初始化新的HttpWebRequest对象。如果统一资源标识符方案是"http://"或"https://"时,Create()则返回HttpWebResponse对象。

  详细过程及代码如下:

 1、创建httpWebRequest对象,HttpWebRequest不能直接通过new来创建,只能通过WebRequest.Create(url)的方式来获得。 WebRequest是获得一些应用层协议对象的一个统一的入口(工厂模式),它根据参数的协议来确定最终创建的对象类型。

2、初始化HttpWebRequest对象,这个过程提供一些http请求常用的标头属性:agentstring,contenttype等,其中agentstring比较有意思,它是用来识别你用的浏览器名字的,通过设置这个属性你可以欺骗服务器你是一个IE,firefox甚至是mac里面的safari。

很多认真设计的网站都会根据这个值来返回对不同浏览器特别优化的代码。

3、附加要POST给服务器的数据到HttpWebRequest对象,附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。

4、读取服务器的返回信息,读取服务器返回的时候,要注意返回数据的encoding,如果我们提供的解码类型不对,会造成乱码,比较常见的是utf-8和gb2312。通常,网站会把它编码的方式放在http header里面,如果没有,我们只能通过对返回二进制值的统计方法来确定它的编码方式。

 =====================================================================

=================================  

 const string sUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 

const string sContentType = "application/x-www-form-urlencoded"; 

const string sRequestEncoding = "ascii"; 

const string sResponseEncoding = "utf-8"; 

/// <summary> 

/// 1:Post data to url 

/// </summary> 

/// <param name="data">要post的数据</param> 

/// <param name="url">目标url</param> 

/// <returns>服务器响应</returns> 

static string PostDataToUrl(string data, string url) 

  Encoding encoding = Encoding.GetEncoding(sRequestEncoding); 

  byte[] bytesToPost = encoding.GetBytes(data); 

  return PostDataToUrl(bytesToPost, url); 

 

 

/// <summary> 

/// Postdata to url 

 /// </summary> 

/// <param name="data">要post的数据</param> 

/// <param name="url">目标url</param> 

/// <returns>服务器响应</returns> 

static string PostDataToUrl(byte[] data, string url) 

 { 

  //创建httpWebRequest对象

   System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url); 

  System.Net.HttpWebRequest httpRequest = webRequest as System.Net.HttpWebRequest; 

  if (httpRequest == null) 

  { 

    throw new ApplicationException(string.Format("Invalid url string: {0}", url)); 

  } 

   //填充httpWebRequest的基本信息

 

  httpRequest.UserAgent = sUserAgent; 

   httpRequest.ContentType = sContentType; 

  httpRequest.Method = "POST"; 

   //填充并发送要post的内容

   httpRequest.ContentLength = data.Length; 

  Stream requestStream = httpRequest.GetRequestStream(); 

  requestStream.Write(data, 0, data.Length); 

  requestStream.Close(); 

//发送post请求到服务器并读取服务器返回信息

   Stream responseStream = null;  

  try 

  { 

    responseStream = httpRequest.GetResponse().GetResponseStream(); 

  } 

  catch (Exception e) 

  { 

    throw e; 

  } 

  //读取服务器返回信息

   string stringResponse = string.Empty; 

  using (StreamReader responseReader = new StreamReader(responseStream, 

  Encoding.GetEncoding(sResponseEncoding))) 

  { 

    stringResponse = responseReader.ReadToEnd(); 

  } 

  responseStream.Close(); 

  return stringResponse; 

//调用

 string contentHtml = PostDataToUrl("ename=simon&des=87cool", "http://www.87cool.com"); 

C# HttpWebRequest提交数据方式. 使用 GET 方式提交中文数据。
GET 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种,用 gb2312
方式编码访问的程序代码如下:
       
Encoding myEncoding = Encoding.GetEncoding("gb2312"); 
string address = "http://www.baidu.com/s?"   + HttpUtility.UrlEncode("参数一", myEncoding) +  "=" + HttpUtility.UrlEncode("值一", myEncoding);

HttpWebRequest req =   (HttpWebRequest)HttpWebRequest.Create(address); req.Method = "GET";  

using (WebResponse wr = req.GetResponse())  
  {  
         //在这里对接收到的页面内容进行处理  
  }  

在上面的程序代码中,我们以 GET 方式访问了网址 http://www.baidu.com/s,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。常见的网站中, www.baidu.com(百度)的编码方式是gb2312,www.google.com (谷歌)的编码方式是 utf8。

C# HttpWebRequest提交数据方式4. 使用 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.baidu.com/s" ); 
            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()) 
            { 
               //在这里对接收到的页面内容进行处理 
            }  
         

 

 //附加一个HttpWebRequest的一个小例子

 /// <summary> 

/// 小例子

2:直接请求,保存远程图片到本地

 /// </summary> 

static void SaveRemoteImg() 

   System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("http://www.87cool.com.logo.gif"); 

  httpRequest.Timeout = 150000; 

  System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)httpRequest.GetResponse(); 

  System.Drawing.Image img = new 

  System.Drawing.Bitmap(resp.GetResponseStream()); 

  img.Save("/87cool.com.gif"); 

 

=====================================================================

===================  

posted on 2014-08-29 14:53  走过路过ボ不要错过  阅读(6412)  评论(0编辑  收藏  举报

导航