c#模拟Http请求

时间:2021-08-18 00:48:44

一、POST请求 

参数 paramsValue的格式 要和 Reques.ContentType一致,

如果 contentype  "application/x-www-form-urlencoded" 表单类型,那么  参数为   a=1&b=2 形式

如果 contentype  "application/json"  json 类型  那么参数就为  "{a:1,b:2}" 格式

1.参数类型: ContentType = "application/x-www-form-urlencoded"

(1)发起请求的方法体

注:参数是自定义实体类

public object GetPost([FromBody]RequestTest request) { return HttpHelper.HttpPostForm(":56188/IDCardOCR/Test",request); }

(2)模拟请求封装

首先封装参数

public static string BuildFrom<T>(T requestFrom) { string form = string.Empty; foreach (var property in requestFrom.GetType().GetProperties()) { form += property.Name.ToLower() + "=" + property.GetValue(requestFrom).ToString() + "&"; } form = form.TrimEnd(&); return form; }

模拟请求实体

public static object HttpPostForm(string url, RequestTest requestFrom) { string form = BuildFrom<RequestTest>(requestFrom); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; byte[] paramload = System.Text.Encoding.UTF8.GetBytes(form); request.ContentLength = paramload.Length; Stream writer = request.GetRequestStream(); writer.Write(paramload, 0, paramload.Length); writer.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream s = response.GetResponseStream(); StreamReader Reader = new StreamReader(s, Encoding.UTF8); object strValue = Reader.ReadLine(); return strValue; }

2.参数类型: ContentType = "application/json; charset=utf-8"

以上几种模拟请求的接收实体

注:Cup是自定义接收实体

[HttpPost("Test")] public int Test(Cup cup) { return cup.a + cup.b; }

标签:

原文地址:https://www.cnblogs.com/yxcn/p/11551703.html