使用HttpWebRequest发送模拟POST请

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

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


MSDN对HttpWebRequest和HttpWebResponse的说明:

这里简要介绍如何使用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>
/// Post data 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");



//附加一个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 @ 2012-07-05 12:18  好运博客  阅读(555)  评论(1编辑  收藏  举报