WebRequest 对象的使用

本文提供了一个使用C#实现HTTP POST请求的具体示例代码,包括设置请求头、编码请求参数、发送请求并读取响应结果的过程。

调用格式:

            string url = "http://localhost:26314/HttpPost.ashx?";
            string postDate = "userid=1&username=李四";
            HttpPost(url, postDate);

 

c#代码:

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="uri">请求的地址:</param>
        /// <param name="postData">参数</param>
        /// <returns></returns>
        string HttpPost(string uri, string postData)
        {
            WebRequest webRequest = WebRequest.Create(uri);
            webRequest.ContentType = "application/x-www-form-urlencoded"; // 设置请求的参数形式
            webRequest.Method = "POST";
            byte[] bytes = Encoding.UTF8.GetBytes(postData); //指定编码格式

            webRequest.ContentLength = bytes.Length; // 设置请求参数的长度.

            Stream inStream = null;
            try
            {
                inStream = webRequest.GetRequestStream(); //取得发向服务器的流
                inStream.Write(bytes, 0, bytes.Length);  //发送
            }
            catch (WebException ex)
            {
                return ex.Message.ToString();
            }
            finally
            {
                if (inStream != null)
                {
                    inStream.Close();
                }
            }

            StreamReader readStream = null;
            try
            {
                WebResponse webResponse = webRequest.GetResponse(); // 等待返回结果
                if (webResponse == null)
                { 
                    return null;
                }
                 readStream = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                return readStream.ReadToEnd().Trim();
            }
            catch (WebException ex)
            {
                return ex.Message.ToString();
            }

            finally
            {
                if (readStream != null)
                {
                    readStream.Close();
                }
            }
        }

 

            

 

转载于:https://www.cnblogs.com/bweb/p/4708685.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值