码迷,mamicode.com
首页 > Windows程序 > 详细

c#模拟Http请求

时间:2019-09-19 19:31:18      阅读:142      评论:0      收藏:0      [点我收藏+]

标签: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>(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;
}

 

c#模拟Http请求

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!