Explain c#. Net core network request in detail

Time:2021-9-21

This article is under the environment of vs2017, and the version of. Net core is above 1.1.

During this period, because. Net core is not based on IIS, our past network request codes may be incompatible and report errors under the. Net core framework. Here is a general introduction to how to make HTTP requests under. Net core. The main methods are still get and post. If there are errors, please correct them!

Let’s start with post. I have implemented three methods for post. The principles of the first two methods are completely consistent, and there are some small differences in the latter, but they are essentially HTTP requests. They are essentially indistinguishable, but the implementation methods are different.

No more nonsense, code:

Post asynchronous method:

/// <summary>
    ///Asynchronous request post (in the form of key value pair, can wait)
    /// </summary>
    ///< param name = "URI" > network base address(“ http://localhost:59315 ")</param>
    ///< param name = "URL" > network address ("/ 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" > encoding 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 pair)
    /// </summary>
    ///< param name = "URI" > network base address(“ http://localhost:59315 ")</param>
    ///< param name = "URL" > network address ("/ 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" > encoding 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. I think it will increase the system overhead. If you have other efficient implementations, please don’t hesitate to comment!

Next, post through 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 the HTTP response as a character stream
        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();
      }
    }

In this way, the data is still written into the stream for post. The reason why the first two key value forms are written is to conform to the style of Java or OC. In c# written webapi, since the receiving form is {= value} rather than {key = value} (determined by the nature of webapi), I will talk about how to receive (key value) in webapi later, Appropriately avoid the contradiction between. Net background personnel and Android and IOS, so as to achieve the long-term stability of socialist democratic society.

The next step is get. Similarly, synchronous and asynchronous are implemented asynchronously. Please spray gently.

GET:

/// <summary>
    ///Asynchronous request get (UTF-8)
    /// </summary>
    ///< param name = "URL" > link address < / param >    
    ///< param name = "formdata" > content written in header < / 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>
    ///Synchronize get requests
    /// </summary>
    ///< param name = "URL" > link address < / param >    
    ///< param name = "formdata" > key value pairs written in header < / 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;
    }

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.