C# 发送get和post 请求有好几种方法
(1)利用 HttpWebRequest 、 HttpWebResponse 这一对来写代码【最原始的,有很有用的】
(2)利用 WebClient 发送【其实内在还是用到了上面的一对,只是微软封装了一层,简单些】
(3)利用 HttpClient发送【这个是 net framework 4.6以后推荐的,对异步编程更友善】
我这里看了msdn之后,用webClient写了一个方法,经常用,简单点。
https://docs.microsoft.com/zh-cn/dotnet/api/system.net.webclient?view=netframework-4.6
代码如下
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
namespace WebTestGP.Models
{
public class HttpHelper
{
public static string GetData(string url, NameValueCollection namevalue)
{
string responseData = "";
try
{
if (namevalue.Count > 0)
{
string para = "";
for (int i = 0; i < namevalue.Count; i++)
{
para += string.Format("&{0}={1}", namevalue.GetKey(i), namevalue.Get(i));
}
para = "?" + para.TrimStart('&');
url += para;
//get请求需要把 url?para1=11¶2=22 补充上
}
using (var client = new WebClient())
{
byte[] data = client.DownloadData(url);
responseData = Encoding.UTF8.GetString(data);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return responseData;
}
public static string PostData(string url, NameValueCollection namevalue)
{
string responseData = "";
try
{
using (var client = new WebClient())
{
byte[] bytes = client.UploadValues(url, namevalue);
responseData = Encoding.UTF8.GetString(bytes);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return responseData;
}
}
}
使用例子
System.Collections.Specialized.NameValueCollection namevalue = new System.Collections.Specialized.NameValueCollection();
namevalue["ag"] = "15";
namevalue["na"] = "wang";
namevalue["dt"] = "2021-8-5";
string get4= HttpHelper.GetData("http://localhost:63341/api/test/g", namevalue);
System.Collections.Specialized.NameValueCollection namevalue2 = new System.Collections.Specialized.NameValueCollection();
namevalue2["age"] = "18";
namevalue2["name"] = "LI";
namevalue2["InSchool"] = "2021-08-16";
string post4 = HttpHelper.PostData("http://localhost:63341/api/test/p", namevalue2);
如果觉得get 方法构造parameter 比较奇怪,其实可以直接传入一个string 字符串, 不用nameValue或者dictionary来构造参数。