程序内部或controller中发起post请求,调用http接口

本文提供了一个使用C#发起HTTP POST请求的代码示例。该示例展示了如何设置请求头、编码请求参数并读取服务器响应。对于需要与HTTP API交互的开发者来说,这是一个实用的参考。

经常会在程序内部调用http方式的接口,直接发起post请求。一下为代码示例:url为请求地址,param为携带的参数

         public static string Post(string url, string param)
         {
             System.Text.Encoding myEncode = System.Text.Encoding.GetEncoding("UTF-8");
             byte[] postBytes = System.Text.Encoding.ASCII.GetBytes(param);


             HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
             req.Method = "POST";
             //req.KeepAlive = false;
             req.ContentType = "application/x-www-form-urlencoded";
             req.ContentLength = postBytes.Length;

             try
             {
                 using (Stream reqStream = req.GetRequestStream())
                 {
                     reqStream.Write(postBytes, 0, postBytes.Length);
                 }

                 using (WebResponse res = req.GetResponse())
                 {
                     using (StreamReader sr = new StreamReader(res.GetResponseStream(), myEncode))
                     {
                         string strResult = sr.ReadToEnd();
                         return strResult;
                     }
                 }

             }
             catch (WebException ex)
             {
                 return "无法连接到服务器\r\n错误信息:" + ex.Message;
             }

         }




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值