后台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
推荐阅读
-
无论GET还是POST都可以用通用方式获取请求参数
-
PHP中使用socket方式GET、POST数据实例教程
-
PHP中使用cURL实现Get和Post请求的方法
-
PHP中使用socket方式GET、POST数据实例_php实例
-
php 利用socket发送HTTP请求(GET,POST),socketget_PHP教程
-
PHP下使用CURL方式POST数据至API接口的代码_PHP
-
PHP模拟发送POST请求之三、加强file_get_contents发送POST请求
-
post请求重定向到get请求问题
-
php自定义类fsocket模拟post或get请求的方法_PHP
-
PHP下使用CURL方式POST数据至API接口的代码