Detailed introduction to the example code sharing of network requests under C# .net core

黄舟
Release: 2017-05-28 10:05:07
Original
1589 people have browsed it

This article mainly introduces the detailed explanationc# Network requests under .net core. It briefly introduces how to make http requests under .net core. The main methods are still GET and POST. If you are interested, you can Understand

This article is in the VS2017 environment, .net core version 1.1 or above.

During this period, since .net core is not based on IIS, our past network request code may be incompatible and error reporting under the .net coreframework. Here is a general introduction on how to make http requests under .net core. The main methods are still GET and POST. If there are any errors, please correct me!

Let’s talk about POST first. I have implemented three methods for POST. The first two are based on the same principles. There are some small differences in the latter ones, but their essence is http request. In essence, There is no difference, just the implementation method is different.

Without further ado, here’s the code:

POST asynchronous method:

 /// <summary>
    /// 异步请求post(键值对形式,可等待的)
    /// </summary>
    /// <param name="uri">网络基址("http://localhost:59315")</param>
    /// <param name="url">网络的地址("/api/UMeng")</param>
    /// <param name="formData">键值对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">编码格式</param>
    /// <param name="mediaType">头媒体类型</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;
    }
Copy after login

POST synchronous method:

/// <summary>
    /// 同步请求post(键值对形式)
    /// </summary>
    /// <param name="uri">网络基址("http://localhost:59315")</param>
    /// <param name="url">网络的地址("/api/UMeng")</param>
    /// <param name="formData">键值对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">编码格式</param>
    /// <param name="mediaType">头媒体类型</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;
    }
Copy after login

Unfortunately, the synchronous method is also based on asynchronous implementation. I personally think that doing so will increase system overhead. If you have other efficient implementations, please feel free to let me know!

The next step is to perform POST through the stream:

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;
      }
    }
Copy after login
private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
    {
      Stream stream = null;
      StreamReader reader = null;

      try
      {
        // 以字符流的方式读取HTTP响应
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        return reader.ReadToEnd();
      }
      finally
      {
        // 释放资源
        if (reader != null) reader.Dispose();
        if (stream != null) stream.Dispose();
        if (rsp != null) rsp.Dispose();
      }
    }
Copy after login

This method of POST still writes the data into the stream and performs POST. The reason why the first two key-values ​​are written is The form is to conform to the style of Java or OC. In the webapi written in C#, since the receiving form is {=value} instead of {key=value} (determined by the nature of the webapi), I will talk about how to receive it in the webapi later. (key-value) form, appropriately avoid conflicts between .net backend personnel and android and ios, thereby achieving long-term stability in a socialist democratic society.

Next is get. Similarly, synchronous and asynchronous are all implemented by asynchronous, please read it lightly.

GET:

 /// <summary>
    /// 异步请求get(UTF-8)
    /// </summary>
    /// <param name="url">链接地址</param>    
    /// <param name="formData">写在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;
    }
Copy after login
rrree

The above is the detailed content of Detailed introduction to the example code sharing of network requests under C# .net core. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template