HTTP 模拟post请求

#region 构造URL POST请求
        /// <summary>
        /// 获取请求的反馈信息
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="bData">参数字节数组</param>
        /// <returns>响应内容</returns>
        private static String doPostRequest(string url, byte[] bData)
        {
            HttpWebRequest hwRequest;
            HttpWebResponse hwResponse;

            string strResult = string.Empty;
            //.net(客户端)调用php(服务端)出现417错误
            try
            {
                ServicePointManager.Expect100Continue = false;//远程服务器返回错误: (417) Expectation failed 异常源自HTTP1.1协议的一个规范: 100(Continue)
                hwRequest = (HttpWebRequest)WebRequest.Create(url);
                hwRequest.Timeout = 2000;
                hwRequest.Method = "POST";
                hwRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                hwRequest.ContentLength = bData.Length;
                Stream smWrite = hwRequest.GetRequestStream();
                smWrite.Write(bData, 0, bData.Length);
                smWrite.Close();
            }
            catch
            {
                return strResult;
            }

            //get response
            try
            {
                hwResponse = (HttpWebResponse)hwRequest.GetResponse();
                StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.UTF8);
                strResult = srReader.ReadToEnd();
                srReader.Close();
                hwResponse.Close();
            }
            catch
            {
                return strResult;
            }

            return strResult;
        }
        #endregion

        #region POST请求
        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="param">参数字符串</param>
        /// <returns>响应内容</returns>
        public static string PostMethod(string url, string param)
        {
            byte[] data = Encoding.UTF8.GetBytes(param);
            return doPostRequest(url, data);
        }
        #endregion
调用 string value=PostMethod("http://www.csdn.net/","username=aaa&password=bbbbb");
    if(value==""){
	Responese.Write("空值");
} else{
Response.Write(value);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值