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

来源:互联网 发布:淘宝px是什么意思 编辑:程序博客网 时间:2024/06/04 19:41

经常会在程序内部调用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;             }         }


                                             
0 0
原创粉丝点击