Explain the network request under c. net core in detail

  • 2021-09-20 19:55:52
  • OfStack

This article is in the context of VS 2017, net core version 1.1 and above.

During this period, because. net core is not based on IIS, our past network request codes may be incompatible and error-reporting under the framework of. net core. Here is a general introduction to how to request http under. net core, mainly GET and POST methods. If there are mistakes, please correct me!

First of all, I have implemented three methods for POST and POST. The first two are based on completely identical principles, while the latter are slightly different, but their essence is http request, which is essentially indistinguishable, but the implementation methods are different.

Needless to say, put on the code:

POST asynchronous method:


 /// <summary>
    ///  Asynchronous request post (Key-value pair form , Waitable) 
    /// </summary>
    /// <param name="uri"> Network base address ("http://localhost:59315")</param>
    /// <param name="url"> The address of the network ("/api/UMeng")</param>
    /// <param name="formData"> Key-value pair List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();formData.Add(new KeyValuePair<string, string>("userid", "29122"));formData.Add(new KeyValuePair<string, string>("umengids", "29122"));</param>
    /// <param name="charset"> Coding format </param>
    /// <param name="mediaType"> Header media type </param>
    /// <returns></returns>
    public async Task<string> HttpPostAsync(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded")
    {
      
      string tokenUri = url;
      var client = new HttpClient();
      client.BaseAddress = new Uri(uri);
      HttpContent content = new FormUrlEncodedContent(formData);
      content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
      content.Headers.ContentType.CharSet = charset;
      for (int i = 0; i < formData.Count; i++)
      {
        content.Headers.Add(formData[i].Key, formData[i].Value);
      }
      
      HttpResponseMessage resp = await client.PostAsync(tokenUri, content);
      resp.EnsureSuccessStatusCode();
      string token = await resp.Content.ReadAsStringAsync();
      return token;
    }

POST synchronization method:


/// <summary>
    ///  Synchronization request post (In the form of key-value pairs) 
    /// </summary>
    /// <param name="uri"> Network base address ("http://localhost:59315")</param>
    /// <param name="url"> The address of the network ("/api/UMeng")</param>
    /// <param name="formData"> Key-value pair List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();formData.Add(new KeyValuePair<string, string>("userid", "29122"));formData.Add(new KeyValuePair<string, string>("umengids", "29122"));</param>
    /// <param name="charset"> Coding format </param>
    /// <param name="mediaType"> Header media type </param>
    /// <returns></returns>
    public string HttpPost(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded")
    {      
      string tokenUri = url;
      var client = new HttpClient();
      client.BaseAddress = new Uri(uri);
      HttpContent content = new FormUrlEncodedContent(formData);
      content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
      content.Headers.ContentType.CharSet = charset;
      for (int i = 0; i < formData.Count; i++)
      {
        content.Headers.Add(formData[i].Key, formData[i].Value);
      }

      var res = client.PostAsync(tokenUri, content);
      res.Wait();
      HttpResponseMessage resp = res.Result;
      
      var res2 = resp.Content.ReadAsStringAsync();
      res2.Wait();

      string token = res2.Result;
      return token;
    }

Unfortunately, the synchronous method is also based on asynchronous implementation, which I think will increase the system overhead. If you have other efficient implementations, please feel free to comment!

Next, POST is carried out by streaming:


public string Post(string url, string data, Encoding encoding, int type)
    {
      try
      {
        HttpWebRequest req = WebRequest.CreateHttp(new Uri(url));
        if (type == 1)
        {
          req.ContentType = "application/json;charset=utf-8";
        }
        else if (type == 2)
        {
          req.ContentType = "application/xml;charset=utf-8";
        }
        else
        {
          req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
        }

        req.Method = "POST";
        //req.Accept = "text/xml,text/javascript";
        req.ContinueTimeout = 60000;

        byte[] postData = encoding.GetBytes(data);
        Stream reqStream = req.GetRequestStreamAsync().Result;
        reqStream.Write(postData, 0, postData.Length);
        reqStream.Dispose();

        var rsp = (HttpWebResponse)req.GetResponseAsync().Result;
        var result = GetResponseAsString(rsp, encoding);
        return result;
        
      }
      catch (Exception ex)
      {
        throw;
      }
    }


private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
    {
      Stream stream = null;
      StreamReader reader = null;

      try
      {
        //  Read as a character stream HTTP Response 
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        return reader.ReadToEnd();
      }
      finally
      {
        //  Release resources 
        if (reader != null) reader.Dispose();
        if (stream != null) stream.Dispose();
        if (rsp != null) rsp.Dispose();
      }
    }

POST in this way still writes data into the stream, For POST, the first two key-value forms are written in order to conform to the style of java or oc. In webapi written by c #, because the receiving form is {= value} instead of {key=value} (determined by the nature of webapi), I will talk about how to receive (key-value) in webapi.

Next is get, which is also synchronized and asynchronous. Please spray it lightly.

GET:


 /// <summary>
    ///  Asynchronous request get(UTF-8)
    /// </summary>
    /// <param name="url"> Link address </param>    
    /// <param name="formData"> Written in header Content in </param>
    /// <returns></returns>
    public static async Task<string> HttpGetAsync(string url, List<KeyValuePair<string, string>> formData = null)
    {
      HttpClient httpClient = new HttpClient();
      HttpContent content = new FormUrlEncodedContent(formData);
      if (formData != null)
      {
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        content.Headers.ContentType.CharSet = "UTF-8";
        for (int i = 0; i < formData.Count; i++)
        {
          content.Headers.Add(formData[i].Key, formData[i].Value);
        }
      }
      var request = new HttpRequestMessage()
      {
        RequestUri = new Uri(url),
        Method = HttpMethod.Get,
      };
      for (int i = 0; i < formData.Count; i++)
      {
        request.Headers.Add(formData[i].Key, formData[i].Value);
      }
      var resp = await httpClient.SendAsync(request);
      resp.EnsureSuccessStatusCode();
      string token = await resp.Content.ReadAsStringAsync();

      return token;
    }


 /// <summary>
    ///  Synchronization get Request 
    /// </summary>
    /// <param name="url"> Link address </param>    
    /// <param name="formData"> Written in header Key-value pairs in </param>
    /// <returns></returns>
    public string HttpGet(string url, List<KeyValuePair<string, string>> formData = null)
    {
      HttpClient httpClient = new HttpClient();
      HttpContent content = new FormUrlEncodedContent(formData);
      if (formData != null)
      {
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        content.Headers.ContentType.CharSet = "UTF-8";
        for (int i = 0; i < formData.Count; i++)
        {
          content.Headers.Add(formData[i].Key, formData[i].Value);
        }
      }
      var request = new HttpRequestMessage()
      {
        RequestUri = new Uri(url),
        Method = HttpMethod.Get,
      };
      for (int i = 0; i < formData.Count; i++)
      {
        request.Headers.Add(formData[i].Key, formData[i].Value);
      }
      var res = httpClient.SendAsync(request);
      res.Wait();
      var resp = res.Result;
      Task<string> temp = resp.Content.ReadAsStringAsync();
      temp.Wait();
      return temp.Result;
    }


Related articles: