C#代码的方式发送POST和GET请求。
引入命名空间
1 2 3 4 5 6 |
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Web; |
C#发送POST的请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/// <summary> /// 后台发送POST请求 /// </summary> /// <param name="url">服务器地址</param> /// <param name="data">发送的数据</param> /// <returns></returns> public string HttpPost(string url, string data) { try { //创建post请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; byte[] payload = Encoding.UTF8.GetBytes(data); request.ContentLength = payload.Length; //发送post的请求 Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); //接受返回来的数据 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.UTF8); string value = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); return value; } catch (Exception) { return ""; } } |
C#发送GET请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/// <summary> /// 后台发送GET请求 /// </summary> /// <param name="url">服务器地址</param> /// <param name="data">发送的数据</param> /// <returns></returns> public string HttpGet(string url, string data) { try { //创建Get请求 url = url + (data == "" ? "" : "?") + data; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; //接受返回来的数据 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8")); string retString = streamReader.ReadToEnd(); streamReader.Close(); stream.Close(); response.Close(); return retString; } catch (Exception) { return ""; } } |
1 |
<br> |
发布者:柚子,转转请注明出处:https://ityouzi.com/archives/http-post-get.html