欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

后台Post/Get 请求接口 方式

程序员文章站 2022-04-15 17:34:43
...

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     }

 


更多专业前端知识,请上【猿2048】www.mk2048.com