亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發布時間:2020-07-13 14:02:39 來源:億速云 閱讀:1394 作者:Leah 欄目:編程語言

這篇文章將為大家詳細講解有關如何在.net core 下進行http請求,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

本文章是在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;
    }

關于如何在.net core 下進行http請求就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

巴中市| 怀安县| 东平县| 绥阳县| 河津市| 宁波市| 鹤岗市| 佛学| 临桂县| 龙南县| 清原| 汤阴县| 沁源县| 安陆市| 哈巴河县| 湖口县| 武定县| 嘉义市| 蓬莱市| 改则县| 堆龙德庆县| 象州县| 叙永县| 揭阳市| 昭平县| 湘潭县| 涞源县| 台北市| 石门县| 濉溪县| 普兰店市| 拜城县| 鹿邑县| 双城市| 佛教| 开平市| 正镶白旗| 康乐县| 绥中县| 轮台县| 宝山区|