范例代码下载
平时用浏览器看网页的时候,点击一下submit按钮的时候其实就是给服务器发送了
一个POST请求。但是如何在自己的C#程序里面实现类似的功能呢?本 文给出了一
个简单的范例,可以实现类似的和web server之间的POST通讯。通过程序发送
POST的过程如下所示:
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 之间的混淆,据 我测试,国内的主机
一般都是gb2312 编码的。一般设计良好的网站会把它编码的方式放在返回的http
header里面,但是也有不少网站根本没有,我们只能通过一个对返回二进制值的统
计方法来确定它的编码方式。
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
namespace SimpleWebRequest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(
PostDataToUrl("test", "http://www.microsoft.com")
);
}
///
/// Post data 到 url
///
///
要 post 的数据
///
目标 url
///
服务器响应
static string PostDataToUrl(string data, string url)
{
Encoding encoding = Encoding.GetEncoding(sRequestEncoding);
byte[] bytesToPost = encoding.GetBytes(data);
return PostDataToUrl(bytesToPost, url);
}
///
/// Post data 到 url
///
///
要 post 的数据
///
目标 url
///
服务器响应
static string PostDataToUrl(byte[] data, string url)
{
#region 创建 httpWebRequest 对象
WebRequest webRequest = WebRequest.Create(url);
HttpWebRequest httpRequest = webRequest as HttpWebRequest;
if (httpRequest == null)
{
throw new ApplicationException(
string.Format("Invalid url string: {0}", url)
);
}
#endregion
#region 填充 httpWebRequest 的基本信息
httpRequest.UserAgent = sUserAgent;
httpRequest.ContentType = sContentType;
httpRequest.Method = "POST";
#endregion
#region 填充要 post 的内容
httpRequest.ContentLength = data.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
#endregion
#region 发送 post 请求到服务器并读取服务器返回信息
Stream responseStream;
try
{
responseStream =
httpRequest.GetResponse().GetResponseStream();
}
catch(Exception e)
{
// log error
Console.WriteLine(
string.Format("POST 操作发生异常:{0}", e.Message)
);
throw e;
}
#endregion
#region 读取服务器返回信息
string stringResponse = string.Empty;
using(StreamReader responseReader =
new StreamReader(responseStream,
Encoding.GetEncoding(sResponseEncoding)))
{
stringResponse = responseReader.ReadToEnd();
}
responseStream.Close();
#endregion
return stringResponse;
}
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 = "gb2312";
}
}