c#模拟Http请求

2021-02-02 12:13

阅读:558

标签:odi   +=   content   web   static   实体   enc   iter   amr   

一、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("http://localhost:56188/IDCardOCR/Test",request);
}

(2)模拟请求封装

  首先封装参数

public static string BuildFrom(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(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;
}

 

c#模拟Http请求

标签:odi   +=   content   web   static   实体   enc   iter   amr   

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


评论


亲,登录后才可以留言!