網站首頁 編程語言 正文
一、引言
我們有時侯需要在程序里面調用Http接口、請求http資源、編寫http爬蟲等的時候都需要在程序里面進行Http請求。很多人習慣的WebClient、HttpWebRequest在TPL下有很多用起來不方便的地方,TPL下推薦使用HttpClient(using System.Net.Http),而且在.NET Core下已經不在支持WebClient等。
1、發送Get請求
HttpClient發出Get請求獲取文本響應,如下面的代碼:
// 實例化HttpClient對象 HttpClient hc = new HttpClient(); // 發送Get請求獲取 string strContent =await hc.GetStringAsync("http://www.baidu.com");
2、發送Post請求
HttpClient發送Post請求使用Task
- FormUrlEncodedContent:表示用來發送表單格式的請求。
- StringContent:表示用來發送字符串請求。
- MultipartFormDataContent:Multipart發送表單請求,一般帶上傳文件信息。
- StreamContent:發送流內容。
二、實例
下面我們看一個使用HttpClient發送Post請求的實例。我們創建一個MVC項目,控制器里面有三個Post請求的方法,分別模擬三種不同內容的Http請求,代碼如下:
using System.Web; using System.Web.Mvc; namespace HttpClientMVCTestDemo.Controllers { public class LoginRequest { public string userName { get; set; } public string password { get; set; } } public class HttpClientTestController : Controller { // GET: HttpClientTest public ActionResult Index() { return View(); } ////// 發送表單請求 /// /// /// ///[HttpPost] public string Login(string userName, string password) { if (userName == "admin" && password == "123") { return "ok"; } else { return "error"; } } /// /// 發送Json格式的請求 /// /// ///[HttpPost] public string Login2(LoginRequest data) { string userName = data.userName; string password = data.password; if (userName == "admin" && password == "123") { return "ok"; } else { return "error"; } } /// /// 上傳文件 /// /// ///[HttpPost] public string Upload(HttpPostedFileBase file) { string userName = Request.Headers["UserName"]; string password = Request.Headers["Password"]; if (userName == "admin" && password == "123") { // 保存文件 file.SaveAs(Server.MapPath("~/" + file.FileName)); return "ok"; } else { return "error"; } } } }
然后創建一個Winform程序,用來發送Http請求。界面上有三個按鈕,分別發送三種不同內容的Http請求。
1、發送表單內容的請求
我們看下面發送表單請求的代碼:
////// 模擬發送表單內容的Http請求 /// /// /// private async void btnForm_Click(object sender, EventArgs e) { // 實例化對象 HttpClient client = new HttpClient(); Dictionarydic = new Dictionary (); dic["userName"] = "admin"; dic["password"] = "123"; // 參數 FormUrlEncodedContent content = new FormUrlEncodedContent(dic); // 發送post請求 HttpResponseMessage responseMsg = await client.PostAsync("http://localhost:55179/HttpClientTest/login", content); // 返回報文體 // responseMsg.Content // 返回響應頭 // responseMsg.Headers // 返回響應碼 // responseMsg.StatusCode // 獲取返回值 這里確定返回的是字符串,調用string string msg =await responseMsg.Content.ReadAsStringAsync(); MessageBox.Show($"響應碼:{responseMsg.StatusCode.ToString()}"); MessageBox.Show($"返回內容:{msg}"); }
程序運行結果:
點擊“確定”,查看返回內容:
2、發送json格式內容的請求
下面是發送json內容請求的代碼:
////// 發送json /// /// /// private async void btnJson_Click(object sender, EventArgs e) { // json格式的字符串 string jsonData = "{userName:'admin',password:'123'}"; // 實例化對象 HttpClient client = new HttpClient(); StringContent content = new StringContent(jsonData); // 設置contentType,必須要設置 設置為json格式,MVC會自動轉換成Model類型 content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // 發送post請求 HttpResponseMessage responseMsg = await client.PostAsync("http://localhost:55179/HttpClientTest/login2", content); // 獲取返回值 string msg = await responseMsg.Content.ReadAsStringAsync(); MessageBox.Show($"響應碼:{responseMsg.StatusCode.ToString()}"); MessageBox.Show($"返回內容:{msg}"); }
3、上傳文件
看一下上傳文件的代碼:
////// 上傳文件 /// /// /// private async void btnUpload_Click(object sender, EventArgs e) { // 實例化對象 HttpClient client = new HttpClient(); MultipartFormDataContent content = new MultipartFormDataContent(); content.Headers.Add("UserName", "admin"); content.Headers.Add("Password", "123"); using (Stream stream = File.OpenRead(@"F:\數據庫.txt")) { content.Add(new StreamContent(stream), "file", "test.txt"); HttpResponseMessage responseMsg = await client.PostAsync("http://localhost:55179/HttpClientTest/Upload", content); // 返回值 string msg = await responseMsg.Content.ReadAsStringAsync(); MessageBox.Show($"響應碼:{responseMsg.StatusCode.ToString()}"); MessageBox.Show($"返回內容:{msg}"); } }
點擊上傳文件按鈕以后,就能在服務器端看到我們上傳的文件了。
原文鏈接:https://www.cnblogs.com/dotnet261010/p/12342296.html
相關推薦
- 2022-04-09 Nginx 提示10013: An attempt was made to access a soc
- 2022-09-07 python?sklearn?畫出決策樹并保存為PDF的實現過程_python
- 2022-02-06 pecl 安裝出現No releases available for package 解決方案
- 2022-08-03 GoFrame?gtree樹形結構的使用技巧示例_Golang
- 2022-05-08 react實現原生下拉刷新_React
- 2022-10-19 react封裝Dialog彈框的方法_React
- 2022-09-29 shell函數內調用另一個函數(不帶返回值和帶返回值)_linux shell
- 2022-06-12 C語言函數指針數組實現計算器功能_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支