后台Post/Get 请求接口 方式
Posted 666qq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了后台Post/Get 请求接口 方式相关的知识,希望对你有一定的参考价值。
Post请求
1 public string HttpPost(string Url, string postDataStr) 2 { 3 try 4 { 5 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 6 request.Method = "POST"; 7 request.ContentType = "application/x-www-form-urlencoded";//请求方约定好 8 9 byte[] bs = Encoding.UTF8.GetBytes(postDataStr); 10 request.ContentLength = bs.Length; 11 using (Stream reqStream = request.GetRequestStream()) 12 { 13 reqStream.Write(bs, 0, bs.Length); 14 } 15 16 HttpWebResponse response; 17 response = (HttpWebResponse)request.GetResponse(); 18 19 Stream myResponseStream = response.GetResponseStream(); 20 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));//一般参数带中文 用utf-8 21 string retString = myStreamReader.ReadToEnd(); 22 myStreamReader.Close(); 23 myResponseStream.Close(); 24 25 return retString; 26 } 27 catch (Exception ex) 28 { 29 LogHelper.WriteLog(ex.Message, ""); 30 } 31 return null; 32 }
Get 请求
1 public static string Get_Http(string strUrl, int timeout) 2 { 3 string strResult; 4 try 5 { 6 HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl); 7 myReq.Timeout = timeout; 8 HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse(); 9 Stream myStream = HttpWResp.GetResponseStream(); 10 StreamReader sr = new StreamReader(myStream, Encoding.UTF8); 11 StringBuilder strBuilder = new StringBuilder(); 12 while (-1 != sr.Peek()) 13 { 14 strBuilder.Append(sr.ReadLine()); 15 } 16 17 strResult = strBuilder.ToString(); 18 } 19 catch (Exception exp) 20 { 21 strResult = "错误:" + exp.Message; 22 } 23 24 return strResult; 25 }
以上是关于后台Post/Get 请求接口 方式的主要内容,如果未能解决你的问题,请参考以下文章