.net .netcore使用HTTP请求

发送

  • 1

         string _url = "http://localhost:65022/login/getaa";
         string jsonParam = "{\"a\":\"aa\",\"b\":\"bb\",\"c\":\"cc\"}";
         var request = (HttpWebRequest)WebRequest.Create(_url);
         request.Method = "POST";
         request.ContentType = "application/json;charset=UTF-8";
         var byteData = Encoding.UTF8.GetBytes(jsonParam);
         var length = byteData.Length;
         request.ContentLength = length;
         request.ServicePoint.Expect100Continue = false;
         //ServicePointManager.Expect100Continue = false;
         request.Timeout = 500; //是进行后续同步请求时使用 GetResponse 方法等待响应以及 GetRequestStream 方法等待流所允许的毫秒数
         var writer = request.GetRequestStream();
         writer.Write(byteData, 0, length);
         writer.Close();
    
         //接收响应内容
         var response = (HttpWebResponse)request.GetResponse();
         var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
         return responseString.ToString();
    
  • 2

    //字符串数据  可以是 “a=aa&b=bb”
    string data="";
    WebRequest myHttpWebRequest = WebRequest.Create(url);
    myHttpWebRequest.Method = "POST";
    UTF8Encoding encoding = new UTF8Encoding();
    byte[] bytepost = encoding.GetBytes(data);
    myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
    myHttpWebRequest.ContentLength = bytepost.Length;
    Stream newStream = myHttpWebRequest.GetRequestStream();
    newStream.Write(bytepost, 0, bytepost.Length);
    newStream.Close();
    
    //发送成功后接收返回的XML信息
    HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
    Encoding enc = Encoding.GetEncoding("UTF-8");
    Stream stream = response.GetResponseStream();
    StreamReader streamReader = new StreamReader(stream, enc);
    string retstr = streamReader.ReadToEnd();
    return retstr;
    

接收

   var sr = new StreamReader(Request.InputStream);
   var stream = sr.ReadToEnd();

.NET Core 中正确使用 HttpClient
https://blog.csdn.net/qq_42606051/article/details/82702575

你可能感兴趣的:(C#)