HttpWebRequest post几个应用实例

作者:袖梨 2022-06-25


先看个简单的请法度

 代码如下 复制代码

using System;
using System.IO;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Net;
using System.Text;

namespace WebApplication1
{

    [WebService(Namespace = "http://www.111com.net/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(http://www.111com.net);
            Encoding encoding = Encoding.UTF8;
            string param = "ie=utf-8&source=txt&query=hello&t=1327829764203&token=8a7dcbacb3ed72cad9f3fb079809a127&from=auto&to=auto";
            //encoding.GetBytes(postData);
            byte[] bs = Encoding.ASCII.GetBytes(param);
            string responseData = String.Empty;           
            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);
                reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(),encoding))
                {
                    responseData = reader.ReadToEnd().ToString();
                }
                context.Response.Write(responseData);
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


HttpWebRequest 发送 POST 请求实现自动登陆

 代码如下 复制代码




从表单可看到表单有两个表单域,一个是userid另一个是password,所以以POST形式提交的数据应该包含有这两项。
其中POST的数据格式为:
表单域名称1=值1&表单域名称2=值2&表单域名称3=值3……
要注意的是“值”必须是经过HTMLEncode的,即不能包含“<>=&”这些符号。

本例子要提交的数据应该是:

 代码如下 复制代码

userid=value1&password=value2
string strId = "guest";
string strPassword= "123456";

ASCIIEncoding encoding=new ASCIIEncoding();
string postData="userid="+strId;
postData += ("&password="+strPassword);

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

// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http:www.here.com/login.asp");

myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();

// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();

// Get response
HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.Default);
string content = reader.ReadToEnd();
Console.WriteLine(content);


使用HttpWebRequest POST数据到服务器上 HTTP协议中,向服务器传递参数的几个位置是: HTTP Header / GET的字符串 / POST中间的Body
下面的示例代码演示如何简单的POST数据到服务器.

 代码如下 复制代码

// 发送请求
string requestBody = string.Format("{0}={1}&{2}={3}&{4}={5}&{6}={7}&{8}={9}"
    , HttpUtility.UrlEncode("version_id", Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode(m_VersionNo, Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode("merchant_id", Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode(m_MerchantID, Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode("verifystring", Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode(hashStr.ToString().ToLower(), Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode("order_date", Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode(m_OrderDate, Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode("order_id", Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode(m_OrderID, Encoding.GetEncoding("GB2312"))
    , HttpUtility.UrlEncode("retmode", Encoding.GetEncoding("GB2312"))
    , string.Empty
    );

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(m_GatewayURL);
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
byte[] aryBuf = Encoding.GetEncoding("GB2312").GetBytes(requestBody);
request.ContentLength = aryBuf.Length;
using(Stream writer = request.GetRequestStream())
{
    writer.Write(aryBuf, 0, aryBuf.Length);
    writer.Close();
    writer.Dispose();
}
string ret = string.Empty;
using (WebResponse response = request.GetResponse())
{
    StreamReader reader = new StreamReader( response.GetResponseStream()
        , Encoding.GetEncoding("GB2312")
        );  
    ret = reader.ReadToEnd();
    reader.Close();
    reader.Dispose();
}

相关文章

精彩推荐