代码改变世界

c#模拟Http请求

2019-09-19 18:43  石吴玉  阅读(2442)  评论(0编辑  收藏  举报

一、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;
}

 (3)此请求有两种接收方式:(不需要参数头部带[FromBody]属性)

     第一种:对象接收

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

    第二种:参数名接收

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

 

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

(1)发起请求的方法体(注:参数是不确定类型的object对象)

[HttpPost("GetPost")]
public object GetPost([FromBody]object request)
{
    return HttpHelper.HttpPostJson("http://localhost:56188/IDCardOCR/Test", request.ToString());
}

(2)模拟请求封装

public static object HttpPostJson(string url, string form)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/json; charset=utf-8";
    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;
}

(3)请求的接收方式(注:要带有[FromBody]属性,且接收参数是个对象)

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