C#中HttpClient進行各種類型的傳輸

我們可以看到, 盡管PostAsync有四個重載函數(shù), 但是接受的都是HttpContent, 而查看源碼可以看到, HttpContent是一個抽象類
那我們就不可能直接創(chuàng)建HttpContent的實例, 而需要去找他的實現(xiàn)類, 經(jīng)過一番研究, 發(fā)現(xiàn)了, 如下四個:
MultipartFormDataContent、FormUrlEncodedContent、StringContent、StreamContent
和上面的總結(jié)進行一個對比就能發(fā)現(xiàn)端倪:
MultipartFormDataContent=》multipart/form-data
FormUrlEncodedContent=》application/x-www-form-urlencoded
StringContent=》application/json等
StreamContent=》binary
而和上面總結(jié)的一樣FormUrlEncodedContent只是一個特殊的StringContent罷了, 唯一不同的就是在mediaType之前自己手動進行一下URL編碼罷了(這一條純屬猜測, 邏輯上應(yīng)該是沒有問題的).
c# 使用HttpClient的post,get方法傳輸json
————————————————文章來源:http://www.zghlxwxcb.cn/news/detail-433250.html
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Timers;
using Newtonsoft.Json;
using System.Net.Http;
using System.IO;
using System.Net;
public class user
{
public string password;//密碼hash
public string account;//賬戶
}
static async void TaskAsync()
{
using (var client = new HttpClient())
{
try
{
//序列化
user user = new user();
user.account = "zanllp";
user.password = "zanllp_pw";
var str = JsonConvert.SerializeObject(user);
HttpContent content =new StringContent(str);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await client.PostAsync("http://255.255.255.254:5000/api/auth", content);//改成自己的
response.EnsureSuccessStatusCode();//用來拋異常的
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync("http://255.255.255.254:5000/api/auth");
response.EnsureSuccessStatusCode();//用來拋異常的
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
}
static void Main(string[] args)
{
TaskAsync();
Console.ReadKey();
}
在阿里云上的.Net Core on Linux
自己封裝的類,我?guī)缀跛械膫€人項目都用這個
using ICSharpCode.SharpZipLib.GZip;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
/// <summary>
/// 基于HttpClient封裝的請求類
/// </summary>
public class HttpRequest
{
/// <summary>
/// 使用post方法異步請求
/// </summary>
/// <param name="url">目標(biāo)鏈接</param>
/// <param name="json">發(fā)送的參數(shù)字符串,只能用json</param>
/// <returns>返回的字符串</returns>
public static async Task<string> PostAsyncJson(string url, string json)
{
HttpClient client = new HttpClient();
HttpContent content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
/// <summary>
/// 使用post方法異步請求
/// </summary>
/// <param name="url">目標(biāo)鏈接</param>
/// <param name="data">發(fā)送的參數(shù)字符串</param>
/// <returns>返回的字符串</returns>
public static async Task<string> PostAsync(string url, string data, Dictionary<string, string> header = null, bool Gzip = false)
{
HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
HttpContent content = new StringContent(data);
if (header != null)
{
client.DefaultRequestHeaders.Clear();
foreach (var item in header)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
HttpResponseMessage response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
string responseBody = "";
if (Gzip)
{
GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
responseBody = new StreamReader(inputStream).ReadToEnd();
}
else
{
responseBody = await response.Content.ReadAsStringAsync();
}
return responseBody;
}
/// <summary>
/// 使用get方法異步請求
/// </summary>
/// <param name="url">目標(biāo)鏈接</param>
/// <returns>返回的字符串</returns>
public static async Task<string> GetAsync(string url, Dictionary<string, string> header = null, bool Gzip = false)
{
HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
if (header != null)
{
client.DefaultRequestHeaders.Clear();
foreach (var item in header)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();//用來拋異常的
string responseBody = "";
if (Gzip)
{
GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
responseBody = new StreamReader(inputStream).ReadToEnd();
}
else
{
responseBody = await response.Content.ReadAsStringAsync();
}
return responseBody;
}
/// <summary>
/// 使用post返回異步請求直接返回對象
/// </summary>
/// <typeparam name="T">返回對象類型</typeparam>
/// <typeparam name="T2">請求對象類型</typeparam>
/// <param name="url">請求鏈接</param>
/// <param name="obj">請求對象數(shù)據(jù)</param>
/// <returns>請求返回的目標(biāo)對象</returns>
public static async Task<T> PostObjectAsync<T, T2>(string url, T2 obj)
{
String json = JsonConvert.SerializeObject(obj);
string responseBody = await PostAsyncJson(url, json); //請求當(dāng)前賬戶的信息
return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
}
/// <summary>
/// 使用Get返回異步請求直接返回對象
/// </summary>
/// <typeparam name="T">請求對象類型</typeparam>
/// <param name="url">請求鏈接</param>
/// <returns>返回請求的對象</returns>
public static async Task<T> GetObjectAsync<T>(string url)
{
string responseBody = await GetAsync(url); //請求當(dāng)前賬戶的信息
return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
}
}
————————————————
版權(quán)聲明:本文為CSDN博主「luckyone906」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/u011555996/article/details/116721769
C# 使用 HttpClient 進行http GET/POST請求文章來源地址http://www.zghlxwxcb.cn/news/detail-433250.html
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace HTTPRequest
{
class Program
{
static void Main(string[] args)
{
HttpClient httpClient = new HttpClient();
Task<byte[]> task0= httpClient.GetByteArrayAsync("http://127.0.0.1");
task0.Wait();
// while (!task0.IsCompletedSuccessfully) { };
byte[] bresult=task0.Result;
string sresult = System.Text.Encoding.Default.GetString(bresult);
Console.WriteLine(sresult);
// Console.ReadLine();
-------
HttpClient httpClient0 = new HttpClient();
List<KeyValuePair<string, string>> param = new List<KeyValuePair<string, string>>();
param.Add(new KeyValuePair<string, string>("xx", "xx"));
Task<HttpResponseMessage> responseMessage =httpClient0.PostAsync("http://localhost:1083/Home/Test", new FormUrlEncodedContent(param));
responseMessage.Wait();
Task<string> reString= responseMessage.Result.Content.ReadAsStringAsync();
reString.Wait();
Console.WriteLine(reString.Result);
Console.ReadLine();
}
}
}
————————————————
版權(quán)聲明:本文為CSDN博主「luckyone906」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/u011555996/article/details/116721769
到了這里,關(guān)于C#中通過HttpClient發(fā)送Post請求的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!