C# 封装网络请求

/// <summary>
    /// 封装POST、GET网络请求
    /// </summary>
    /// <param name="url">请求的接口地址</param>
    /// <param name="method">方法类型GET,POST</param>
    /// <param name="json">json数据</param>
    /// <param name="parm">参数</param>
    /// <returns></returns>
    private static string HttpComm(string url, string method, string json, string parm = "")
    {
        string result = string.Empty;//返回结果
        try
        {
            if (method.ToUpper() == "GET" && parm != "")//GET请求
            {
                url += $"?phone={parm}";
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = method.ToUpper();
            request.ContentType = "application/json;charset=UTF-8";
            if (method.ToUpper() == "POST")//POST请求
            {
                byte[] bytedata = Encoding.UTF8.GetBytes(json);
                int lenght = bytedata.Length;
                request.ContentLength = lenght;
                Stream wirteStream = request.GetRequestStream();
                wirteStream.Write(bytedata, 0, bytedata.Length);
                wirteStream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamResult = response.GetResponseStream();
            //获取内容
            using (StreamReader reader = new StreamReader(streamResult, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
        }
        catch (Exception e)
        {
            var s = e.Message;// SystemConfig.LogInfo(e.Message);
        }
        return result;
    }

二、获取POST请求过来的数据。(于2020-03-28 更新)

/// <summary>
/// 接受用户发送的消息
/// </summary>
[HttpPost]
public string Indexs()
{
  string postString = "无数据";
  if (HttpContext.Request.HttpMethod.ToUpper() == "POST")
  {
      string xmlPath = string.Empty;
      Response.ContentType = "text/plain";
      using (Stream stream = HttpContext.Request.InputStream)
      {
          Byte[] postBytes = new Byte[stream.Length];
          stream.Read(postBytes, 0, (Int32)stream.Length);
          postString = Encoding.UTF8.GetString(postBytes);
          if (string.IsNullOrEmpty(postString))
          {

              postString = "没有数据";
          }
          StreamWriter str = new StreamWriter(@"F:\数据打印.txt", true, Encoding.UTF8);
          str.WriteLine(postString);
          str.Close();
      }
  }
  return postString;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值