Get / Post

HttpWebRequest 是 .net 基类库中的一个类,在命名空间 System.Net 下面,用来使用户通过 HTTP 协议和服务器交互。

HttpWebRequest 对 HTTP 协议进行了完整的封装,对 HTTP 协议中的 Header, Content, Cookie 都做了属性和方法的支持,很容易就能编写出一个模拟浏览器自动登录的程序。

程序使用 HTTP 协议和服务器交互主要是进行数据的提交,通常数据的提交是通过 GET 和 POST 两种方式来完成,下面对这两种方式进行一下说明:

1. GET 方式。

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

HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.google.com/webhp?hl=zh-CN" );
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
   //在这里对接收到的页面内容进行处理
}

2. 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.google.com/intl/zh-CN/" );
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())
{
   //在这里对接收到的页面内容进行处理
}

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

3. 使用 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。

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())
{
   //在这里对接收到的页面内容进行处理
}

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

以上列出了客户端程序使用 HTTP 协议与服务器交互的情况,常用的是 GET 和 POST 方式。现在流行的 WebService 也是通过 HTTP 协议来交互的,使用的是 POST 方法。与以上稍有所不同的是, WebService 提交的数据内容和接收到的数据内容都是使用了 XML 方式编码。所以, HttpWebRequest 也可以使用在调用 WebService 的情况下。

 

 

----------------Html 表单--------------

后台代码获取前台提交的HTML表单数据

 

**********POst 文件上传******************

System.Net.WebClient client = new WebClient();
client.Headers.Add("Accept", "*/*");
client.Headers.Add("Accept-Encoding", "gzip, deflate");
client.Headers.Add("Accept-Language", "zh-cn");
client.Headers.Add("Cache-Control", "no-cache");
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//必填项目
string resposeData = Encoding.Default.GetString(client.UploadFile(@"http://wimg.wangkun.rhythmk/gxkt/",
"POST",
@"C:\Documents and Settings\Administrator\桌面\要上传\rhythmk.jpg"));
Response.Write(resposeData);

 

 

代码
<script runat="server" >
   
    protected 
void Page_Load(object sender, EventArgs e)
    {
      
//Request.From["name"] 可以获取HTML表单提交的Post表单 

        
if (Request.Form.Count > 0)
        {
            
            Response.Write(Request.Form[
"Text1"].ToString());
        }

        
// 将表单的 method="get" ,则可通过Request.QueryString["name"] 可以获取HTML表单提交的Get表单 
        if (Request.QueryString.Count > 0)
        {
           Response.Write(Request.QueryString[
"Text1"].ToString());
             
        }
    }
 
</script>
    
<form id="form1" action="Default8888.aspx" method="post"   >
    
<div>
        
<input id="Text1" type="text" name="Text1"/>  
        
        
<input id="Submit1" type="submit" value="submit" />
        
  
</div>
    
</form>

 

 

        public static void Post(string url)
        {
            string encode = "utf-8";
            Encoding myEncoding = Encoding.GetEncoding(encode);
            string param = HttpUtility.UrlEncode("aa", myEncoding) + "=" + HttpUtility.UrlEncode("a1", myEncoding) 
                + "&" + HttpUtility.UrlEncode("dd", myEncoding) + "=" + HttpUtility.UrlEncode("d3", myEncoding)
                + "&" + HttpUtility.UrlEncode("aa", myEncoding) + "=" + HttpUtility.UrlEncode("123gg456", myEncoding);

            byte[] postBytes = Encoding.ASCII.GetBytes(param);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset="+encode;
            req.ContentLength = postBytes.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(postBytes, 0, postBytes.Length);
            }
            using (WebResponse wr = req.GetResponse())
            {

                System.IO.StreamReader sr = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.GetEncoding(encode));
                Console.Write(sr.ReadToEnd());
            }
        }

  

posted @ 2010-01-18 16:18  Rhythmk  阅读(406)  评论(0编辑  收藏  举报
Rhythmk 个人笔记