1.定义一个POST 公共方法
///HttpWebRequest的POST请求的类型通常有application/x-www-form-urlencoded、application/json、multipart/form-data。
///application/x-www-form-urlencoded是默认的请求类型。
///application/json是Json数据格式的请求类型。
///multipart/form-data是表单数据的请求类型。
///以上三种方式中,multipart/form-data通常用于文件上传。
/// <summary>
/// JSON请求API
/// </summary>
/// <param name="url">地址</param>
/// <param name="jsonStr">JSON字符串</param>
/// <returns></returns>
public static string Post(string url, string jsonStr)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
//req.ContentType = "application/x-www-form-urlencoded";
req.ContentType = "application/json";
//req.Headers.Add("Authorization", "PoJzmqZHM@CmitMCcl8@vIQSL&ro$Kq8");
#region 添加Post 参数
byte[] data = Encoding.UTF8.GetBytes(jsonStr);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
2.直接调用 url地址改成你对应API的地址Get4是对应下面API的名称
/// <summary>
/// 测试方法
/// </summary>
public void test()
{
string url = "https://localhost:7049/WeatherForecast/Get4";
string jsonRequest = JsonConvert.SerializeObject(new List<test> { new test { name = "测试名称" } });
var result = Post(url, jsonRequest);
}
3..API接口设置(这里采用的是.net core 6 API 的默认接口)
[HttpPost(Name = "Get4")]
public IActionResult Get4([FromBody]List<test> test)
{
return new JsonResult(test);
}