首頁  >  文章  >  後端開發  >  在.net core 下如何進行http請求?

在.net core 下如何進行http請求?

零下一度
零下一度原創
2017-05-26 13:36:218853瀏覽

本篇文章主要介紹了詳解c# .net core 下的網路請求,大致介紹下在.net core 下如何進行http請求,主要仍然是GET和POST方法,有興趣的可以了解下

本篇文章是在VS2017的環境下,.net core 1.1版本以上。

在這段期間,由於.net core 並非基於IIS,我們的過去的網路請求代碼在.net core框架下,有可能會出現不相容,報錯的現象。這裡大致介紹下在.net core 下如何進行http請求,主要仍然是GET和POST方法,有錯誤的地方,歡迎指正!

先來說POST,POST我實現了三種方法,前兩種基於的原理是完全一致的,後面的有些小小的差異,但他們的本質都是http請求,本質上是無差別的,只是實作方法有所不同。

廢話不多說,上程式碼:

##POST非同步方法:

 /// <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;
    }

POST同步方法:

/// <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;
    }

遺憾的是,同步方法也是基於非同步實現的,個人認為這樣做會加大系統開銷。如果各位有其他的高效實現,請不吝賜教!

接下來是透過串流的方式進行POST:

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
      {
        // 以字符流的方式读取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();
      }
    }

這種方式的POST還是將資料寫入到流裡面,進行POST,之所以寫前兩個key-value的形式,是為了符合java或oc的風格,在c#書寫的webapi中,由於接收形式是{=value}而不是{key=value}(由webapi的性質決定),後續我會說如何在webapi中接收(key-value)的形式,適當避免.net後台人員與

android和ios的矛盾,從而達到社會主義民主社會的長治久安。

接下來是get,同樣同步非同步都是由非同步實現的,還請各位看官輕噴。

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;
    }
 /// <summary>
    /// 同步get请求
    /// </summary>
    /// <param name="url">链接地址</param>    
    /// <param name="formData">写在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;
    }

【相關推薦】

1. 

.Net Core 之圖形驗證碼

#2. 

.NET Core設定檔載入與DI注入設定資料

3. 

.NET Core CLI工具文件dotnet-publish

# 4. 

詳細介紹ZKEACMS for .Net Core

5. 

分享.net MVC中使用forms驗證實例代碼##6. 

CentOS上運行ZKEACMS的實例教學

#

以上是在.net core 下如何進行http請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn