1. 程式人生 > >Net Core 2.1 HttpClient範例

Net Core 2.1 HttpClient範例

Net Core 2.1 HttpClient請求幫助類

1、需要引用Newtonsoft.Json的nuget包,目前版本為11.0.2
2、添加了一些認證資訊的寫法

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace NetCore_HttpClient { /// <summary> /// HttpClient的幫助類 /// </summary> public class HttpClientHelper { /*Edit Desc: 提取預設的Http Heads UserAgen Author:Xuja Time:2016-5-3 16:46:29*/ private static readonly string userAgen = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
; /// <summary> /// 根據Url地址Get請求返回資料 /// 2015年11月12日14:50:02 /// </summary> /// <param name="url">請求的地址</param> /// <param name="ch_httpcode">http狀態碼</param> /// <returns>字串</returns> public static string GetResponse
(string url, out string httpStatusCode) { httpStatusCode = string.Empty; HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; try { //httpClient.MaxResponseContentBufferSize = 256000; httpClient.DefaultRequestHeaders.Add("user-agent", userAgen); //httpClient = new HttpClient(); //using (HttpClient httpClient = new HttpClient()) //{ httpClient.CancelPendingRequests(); httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); Task<HttpResponseMessage> taskResponse = httpClient.GetAsync(url); taskResponse.Wait(); response = taskResponse.Result; //using (HttpResponseMessage response = taskResponse.Result) //{ //HttpResponseMessage response = httpClient.GetAsync(url).Result; if (response.IsSuccessStatusCode) { Task<System.IO.Stream> taskStream = response.Content.ReadAsStreamAsync(); taskStream.Wait(); //此處會丟擲異常:不支援超時設定,對返回結果沒有影響 System.IO.Stream dataStream = taskStream.Result; System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string result = reader.ReadToEnd(); return result; } //} return null; //} } catch { return null; } finally { if (response != null) { response.Dispose(); } if (httpClient != null) { httpClient.Dispose(); } } } /// <summary> /// 根據Url地址Get請求返回資料 /// xuja /// 2015年11月12日14:50:02 /// </summary> /// <param name="url">請求的地址</param> /// <returns>字串</returns> public static string GetResponse(string url) { HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; try { httpClient.DefaultRequestHeaders.Add("user-agent", userAgen); httpClient.CancelPendingRequests(); httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Add("Authorization", "Basic c2hhb3podXFpYW5nOjEyMzQ1NmE/"); httpClient.DefaultRequestHeaders.Add("Username", "shaozhuqiang"); httpClient.DefaultRequestHeaders.Add("Password", "123456a?"); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); Task<HttpResponseMessage> taskResponse = httpClient.GetAsync(url); taskResponse.Wait(); response = taskResponse.Result; if (response.IsSuccessStatusCode) { Task<System.IO.Stream> taskStream = response.Content.ReadAsStreamAsync(); taskStream.Wait(); System.IO.Stream dataStream = taskStream.Result; System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string result = reader.ReadToEnd(); return result; } return null; } catch { return null; } finally { if (response != null) { response.Dispose(); } if (httpClient != null) { httpClient.Dispose(); } } } /// <summary> /// 根據Url地址Get請求返回實體 /// xuja /// 2015年11月12日14:50:02 /// </summary> /// <param name="url">請求的地址</param> /// <returns>實體</returns> public static T GetResponse<T>(string url) { HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; try { //using (HttpClient httpClient = new HttpClient()) //{ //httpClient.MaxResponseContentBufferSize = 256000; httpClient.DefaultRequestHeaders.Add("user-agent", userAgen); httpClient.CancelPendingRequests(); httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); //HttpResponseMessage response = httpClient.GetAsync(url).Result; Task<HttpResponseMessage> taskResponse = httpClient.GetAsync(url); taskResponse.Wait(); T result = default(T); response = taskResponse.Result; //using (HttpResponseMessage response = taskResponse.Result) //{ if (response.IsSuccessStatusCode) { Task<System.IO.Stream> taskStream = response.Content.ReadAsStreamAsync(); taskStream.Wait(); System.IO.Stream dataStream = taskStream.Result; System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string s = reader.ReadToEnd(); result = JsonConvert.DeserializeObject<T>(s); } //} return result; //} } catch (Exception e) { var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(e.ToString()), ReasonPhrase = "error" }; //throw new HttpResponseException(resp); return default(T); } finally { if (response != null) { response.Dispose(); } if (httpClient != null) { httpClient.Dispose(); } } } /// <summary> /// 處理Get的Url /// des:huyf /// </summary> /// <param name="dic"></param> /// <returns></returns> public static string WithParameters(Dictionary<string, string> dic) { string result = "?"; foreach (var item in dic) { result += item.Key + "=" + item.Value + "&"; } result = result.Remove(result.Length - 1); return result; } /// <summary> /// Post請求返回字元 /// </summary> /// <param name="url">請求地址</param> /// <param name="postData">請求資料</param> /// <returns>字元</returns> public static string PostResponse(string url, string postData) { HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; try { //using (HttpClient httpClient = new HttpClient()) //{ httpClient.MaxResponseContentBufferSize = 256000; httpClient.DefaultRequestHeaders.Add("user-agent", userAgen); httpClient.CancelPendingRequests(); httpClient.DefaultRequestHeaders.Clear(); HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); Task<HttpResponseMessage> taskResponse = httpClient.PostAsync(url, httpContent); taskResponse.Wait(); response = taskResponse.Result; //using (HttpResponseMessage response = taskResponse.Result) //{ //HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) { Task<System.IO.Stream> taskStream = response.Content.ReadAsStreamAsync(); taskStream.Wait(); System.IO.Stream dataStream = taskStream.Result; System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string result = reader.ReadToEnd(); return result; } //} return null; //} } catch { return null; } finally { if (response != null) { response.Dispose(); } if (httpClient != null) { httpClient.Dispose(); } } } /// <summary> /// Post請求返回字元 /// </summary> /// <param name="url">請求地址</param> /// <param name="postData">請求資料</param> /// <returns>字元</returns> public static string PostResponse(string url, object obj) { HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; try { //using (HttpClient httpClient = new HttpClient()) //{ httpClient.MaxResponseContentBufferSize = 256000; httpClient.DefaultRequestHeaders.Add("user-agent", userAgen); httpClient.CancelPendingRequests(); httpClient.DefaultRequestHeaders.Clear(); string postData = JsonConvert.SerializeObject(obj); HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); Task<HttpResponseMessage> taskResponse = httpClient.PostAsync(url, httpContent); taskResponse.Wait(); response = taskResponse.Result; //using (HttpResponseMessage response = taskResponse.Result) //{ //HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) { Task<System.IO.Stream> taskStream = response.Content.ReadAsStreamAsync(); taskStream.Wait(); System.IO.Stream dataStream = taskStream.Result; System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string result = reader.ReadToEnd(); return result; } else { //LogHelper.WriteInfo(typeof(HttpClientHelper), "結果:" + response.StatusCode + "內容:" + JsonConvertTool.SerializeObject(obj)); } //} return null; //} } catch (Exception exception) { //LogHelper.Error("結果:異常 內容:" + JsonConvertTool.SerializeObject(obj) + "ex:" + exception.Message, exception); return null; } finally { if (response != null) { response.Dispose(); } if (httpClient != null) { httpClient.Dispose(); } } } /// <summary> /// Post請求返回實體 /// </summary> /// <param name="url">請求地址</param> /// <param name="postData">請求資料</param> /// <returns>實體</returns> public static T PostResponse<T>(string url, string postData) { HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; try { //using (HttpClient httpClient = new HttpClient()) //{ httpClient.MaxResponseContentBufferSize = 256000; httpClient.DefaultRequestHeaders.Add("user-agent", userAgen); httpClient.CancelPendingRequests(); httpClient.DefaultRequestHeaders.Clear(); HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); T result = default(T); Task<HttpResponseMessage> taskResponse = httpClient.PostAsync(url, httpContent); taskResponse.Wait(); response = taskResponse.Result; //using (HttpResponseMessage response = taskResponse.Result) //{ //HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) { Task<System.IO.Stream> taskStream = response.Content.ReadAsStreamAsync(); taskStream.Wait(); System.IO.Stream dataStream = taskStream.Result; System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string s = reader.ReadToEnd(); result = JsonConvert.DeserializeObject<T>(s); } //} return result; //} } catch { return default(T); } finally { if (response != null) { response.Dispose(); } if (httpClient != null) { httpClient.Dispose(); } } } /// <summary> /// Post請求返回實體 /// </summary> /// <param name="url">請求地址</param> /// <param name="postData">請求資料</param> /// <returns>實體</returns> public static T PostResponse<T>(string url, object obj) { HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; try { //using (HttpClient httpClient = new HttpClient()) //{ httpClient.MaxResponseContentBufferSize

相關推薦

Net Core 2.1 HttpClient範例

Net Core 2.1 HttpClient請求幫助類 1、需要引用Newtonsoft.Json的nuget包,目前版本為11.0.2 2、添加了一些認證資訊的寫法 using Newtonsoft.Json; using System; using System.Collect

[搬運] .NET Core 2.1中改進的堆棧信息

我們 previous http mon 告訴 以及 async 時間 異步 原文 : Stacktrace improvements in .NET Core 2.1 作者 : Ben Adams 譯者 : 張很水 . NET Core 2.1 現在具有可讀的異步堆棧

.net core 2.1 以上SignalR實現

focus rev cep 中心 mov 使用 CA rtu self 本教程教生成實時應用程序使用 ASP.NET Core SignalR 的基礎知識。 SignalR在.net core2.1以前是需要下載 Microsoft.AspNetCore.S

.NET Core 2.1來了!

and 圖片 ++ 切換 href 5.7 AS 同事 編譯型 太棒了! .NET Core 2.0正式發布至今已經過去了大半年,這大半年說長不長說短不短,這段時間裏,我是充分地體會到了微軟的誠意,那就是認認真真打造一個優秀的開源平臺。這大半年的時間裏,微軟一直在為.NE

用ASP.NET Core 2.1 建立規範的 REST API -- HATEOAS

enume edi count DC tutorial 不知道 客戶 自適應 獨立 本文所需的一些預備知識可以看這裏: http://www.cnblogs.com/cgzl/p/9010978.html 和 http://www.cnblogs.com/cgzl/p/90

學習 ASP.NET Core 2.1:集成測試中使用 WebApplicationFactory

UNC enc sta 測試 修改 構造 creat -a msdn WebApplicationFactory 是 ASP.NET Core 2.1 新特性 MVC functional test infrastructure 中帶來的新東東,它封裝了 TestServe

asp.net core 2.1 將控制器抽離到類庫中

cat start service public 網站 類庫 class all app startup.cs的ConfigureServices中添加: public void ConfigureServices(IServiceCollection

樹莓派安裝.net core 2.1

http nbsp 內容 oca mkdir -p 安裝 參考 tro tps 0.更新源 sudo apt-get update 1.安裝依賴 sudo apt-get install curl libunwind8 gettext 2.下載 SDK 或者 RunTi

將 ASP.NET Core 2.0 項目升級至 ASP.NET Core 2.1.3X

微信公眾號 code ima microsoft 訪問 nload 操作 更新 解決辦法 在上一篇文章ASP.Net Core 運行錯誤 Http Error 502.5 解決辦法的最後有提到說,最推薦的升級辦法是從2.0升級到2.1X版本. 操作如下 項目的例子直接使用h

.net Core 2.1 MVC+EF+Redis搭建

文件 dds cookie exception reg direct mvc+ef microsoft encoding 官方學習資料 搭建空MVC框架 1.創建一個空模板 2.創建文件夾 Controllers、Models、Views 3.在Contro

再談使用X.PagedList.Mvc 分頁(ASP.NET Core 2.1

asp ram 默認 mvc 文本 它的 otn package www. 在以前的博文中寫過使用X.PagedList.Mvc組件來對ASP.NET MVC應用程序進行分頁,可以參考此篇隨筆:Asp.net MVC 使用PagedList(新的已更名 為X.PagedLi

ASP.NET core 2.1部署到 Centos 7

-m lrzsz arc -perm 安裝asp.net local ESS port pub 步驟要點: 一、關閉Linuxselinux: 操作方式: 1.永久關閉:打開/etc/selinux/config文件,設置SELINUX=disabled,註意,不是S

Asp.net Core 2.1使用 EF Core 簡單增刪改查操作數據庫

generic nuget ini gen 項目 pub sass .net 增刪改查 Asp.net Core 2.1使用 EF Core 簡單增刪改查操作數據庫 大概步驟如下5步: 1、創建項目(Asp.net Core 2.1項目) 2、項目使用EF Core 3、建

獨立部署asp.net core 2.1 Web應用程式

1.建立asp.net core 2.0  Web應用程式 新增引用: Microsoft.EntityFrameworkCore.Sqlite Microsoft.EntityFrameworkCore.Sqlite.Design 2.配置Sqlite資料庫 修改Startup.cs檔案

獨立部署asp.net core 2.1 Web應用程序

ring tar sign options \n rgs migration 局域網 引用 1.創建asp.net core 2.0 Web應用程序 添加引用: Microsoft.EntityFrameworkCore.Sqlite Microsoft.EntityFr

從零開始學習 asp.net core 2.1 web api 後端api基礎框架(七)-新增一個查詢單筆資料的方法

再寫一個查詢單筆資料的方法: [Route("{id}")] public JsonResult GetProduct(int id) { return new JsonResult(ProductService.Curre

從零開始學習 asp.net core 2.1 web api 後端api基礎框架(六)-把獲取資料的程式碼整理成一個服務

建立一個Services目錄, 然後建立一個 ProductService.cs類 我們把獲取資料的程式碼整理成一個ProductService, 然後保證程式執行的時候, 操作的是同一批資料: namespace CoreBackend.Api.Services { public

從零開始學習 asp.net core 2.1 web api 後端api基礎框架(五)-Routing 路由

路由有兩種方式: Convention-based (按約定), attribute-based(基於路由屬性配置的).  其中convention-based (基於約定的) 主要用於MVC (返回View或者Razor Page那種的). Web api 推薦使用attribute

Asp.net Core 2.1 Kestrel 現在支援 多協議處理(Tcp)

地址:https://github.com/davidfowl/MultiProtocolAspNetCore.git 在一個Kestrel服務上可以同時處理Tcp,Http,Https等多種協議。 通過實現 ConnectionHandler 處理接入連線,ConnectionContext.Trans

asp.net core 2.1 DBfirst MySQL 執行命令出錯

Scaffold-DbContext "Data Source=localhost;Initial Catalog=FriendSourceDB;User ID=root;Password=;" Pomelo.EntityFrameworkCore.MySql -OutputDir EFModel