C#使用HttpClient四種請(qǐng)求數(shù)據(jù)格式:json、表單數(shù)據(jù)、文件上傳、xml?,F(xiàn)在流行前后端分離,后端提供對(duì)應(yīng)服務(wù)接口給前端或跨應(yīng)用程序調(diào)用,如WebAPI等。在調(diào)用這些服務(wù)接口發(fā)送HTTP請(qǐng)求,而.NET為我們提供了HttpWebRequest、HttpClient幾個(gè)類庫來實(shí)現(xiàn)。
一、JSON數(shù)據(jù)格式
application/json
引用
using Newtonsoft.Json;using System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;namespace Fountain.WinConsole.HttpDemo
代碼
static async Task Main(string[] args){ try { using (HttpClient httpClient = new HttpClient()) { User user = new User(); user.username = "ceshi"; user.password = "123456"; string jsonData = JsonConvert.SerializeObject(user); StringContent content = new StringContent(jsonData, Encoding.UTF8); // 設(shè)置HTTP 響應(yīng)上的ContentType --application/json content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); // 請(qǐng)求訪問地址 string url = "https://192.168.20.20/api/user/login"; // 發(fā)出HTTP的Post請(qǐng)求 HttpResponseMessage response = await httpClient.PostAsync(url, content); // 讀取返回結(jié)果 string responseContent = await response.Content.ReadAsStringAsync(); // 將字符轉(zhuǎn)對(duì)象 Result result = JsonConvert.DeserializeObject<Result>(responseContent); } } catch (Exception exception) { Console.WriteLine(exception.Message); } Console.ReadLine();}
二、表單數(shù)據(jù)格式
application/x-www-form-urlencoded
引用
using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System;using System.Collections;using System.Collections.Generic;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
代碼
static async Task Main(string[] args){ try { using (HttpClient httpClient = new HttpClient()) { Dictionary<string,string> user = new Dictionary<string, string> { { "username", "ceshi" }, { "password", "123456" } }; FormUrlEncodedContent content = new FormUrlEncodedContent(user); // 請(qǐng)求訪問地址 string url = "https://192.168.20.20/api/user/login"; // 發(fā)出HTTP的Post請(qǐng)求 HttpResponseMessage response = await httpClient.PostAsync(url, content); // 讀取返回結(jié)果 string responseContent = await response.Content.ReadAsStringAsync(); // 將字符轉(zhuǎn)對(duì)象 Result result = JsonConvert.DeserializeObject<Result>(responseContent); } } catch (Exception exception) { Console.WriteLine(exception.Message); } Console.ReadLine();}
三、文件上傳格式
multipart/form-data
引用
using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
代碼
static async Task Main(string[] args){ try { using (HttpClient httpClient = new HttpClient()) { MultipartFormDataContent multipartContent = new MultipartFormDataContent(); multipartContent.Add(new StringContent("user"), "test"); multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "test.jpg"))), "image", "test.jpg"); // 請(qǐng)求訪問地址 string url = "https://192.168.20.20/api/user/upload"; // 發(fā)出HTTP的Post請(qǐng)求 HttpResponseMessage response = await httpClient.PostAsync(url, multipartContent); // 讀取返回結(jié)果 string responseContent = await response.Content.ReadAsStringAsync(); // 將字符轉(zhuǎn)對(duì)象 Result result = JsonConvert.DeserializeObject<Result>(responseContent); } } catch (Exception exception) { Console.WriteLine(exception.Message); } Console.ReadLine();}}
四、XML數(shù)據(jù)格式
text/xml
引用
using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
代碼
static async Task Main(string[] args){ try { using (HttpClient httpClient = new HttpClient()) { StringBuilder user = new StringBuilder(); user.AppendLine("<usrname>ceshi</usrname>"); user.AppendLine("<password>123456</password>"); string xmlData = user.ToString(); StringContent content = new StringContent(xmlData, Encoding.UTF8); // 設(shè)置HTTP 響應(yīng)上的ContentType --text/xml content.Headers.ContentType = new MediaTypeHeaderValue("text/xml"); // 請(qǐng)求訪問地址 string url = "https://192.168.20.20/api/user/login"; // 發(fā)出HTTP的Post請(qǐng)求 HttpResponseMessage response = await httpClient.PostAsync(url, content); // 讀取返回結(jié)果 string responseContent = await response.Content.ReadAsStringAsync(); // 將字符轉(zhuǎn)對(duì)象 Result result = JsonConvert.DeserializeObject<Result>(responseContent); } } catch (Exception exception) { Console.WriteLine(exception.Message); } Console.ReadLine();}
HttpClient的一些屬性與方法。
屬性:
BaseAddress
獲取或設(shè)置發(fā)送請(qǐng)求時(shí)地址。
DefaultProxy
獲取或設(shè)置全局HTTP請(qǐng)求代理。
DefaultRequestHeaders
獲取請(qǐng)求發(fā)送的標(biāo)題。
DefaultRequestVersion
獲取或設(shè)置請(qǐng)求使用的默認(rèn)HTTP版本。
MaxResponseContentBufferSize
獲取或設(shè)置讀取響應(yīng)內(nèi)容時(shí)要緩沖的最大字節(jié)數(shù)。
Timeout
獲取或設(shè)置請(qǐng)求超時(shí)等待的時(shí)間。
方法:
GetAsync
異步請(qǐng)求獲取指定URI。
GetByteArrayAsync
異步請(qǐng)求獲取指定URI并以字節(jié)數(shù)組的形式返回響應(yīng)。
GetStreamAsync
異步請(qǐng)求獲取指定URI并以流的形式返回響應(yīng)。
GetStringAsync
異步請(qǐng)求獲取指定URI并以字符串的形式返回響應(yīng)正文。
PostAsync
異步將POST請(qǐng)求發(fā)送給指定URI。
Send
發(fā)送帶有指定請(qǐng)求的 HTTP 請(qǐng)求。
SendAsync
以異步操作發(fā)送 HTTP 請(qǐng)求。
閱讀原文:原文鏈接
該文章在 2025/2/17 12:23:54 編輯過