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();
}
ContentType有3种方式可选,这里使用URLEncoded方式,比较简单方便