1. 程式人生 > WINDOWS開發 >c# 使用HttpClient的post,get方法傳輸json

c# 使用HttpClient的post,get方法傳輸json

微軟文件地址https://docs.microsoft.com/zh-cn/dotnet/api/system.net.http.httpclient?view=netframework-4.7.2,只有get。post 的方法找了白天才解決

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();
        }

  技術分享圖片

在阿里雲上的.NetCore on Linux

自己封裝的類,我幾乎所有的個人專案都用這個

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">目標連結</param>
    /// <param name="json">傳送的引數字串,只能用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">目標連結</param>
    /// <param name="data">傳送的引數字串</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">目標連結</param>
    /// <returns>返回的字串</returns>
    public static async Task<string> GetAsync(string url,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">請求物件資料</param>
    /// <returns>請求返回的目標物件</returns>
    public static async Task<T> PostObjectAsync<T,T2>(string url,T2 obj)
    {
        String json = JsonConvert.SerializeObject(obj);
        string responseBody = await PostAsyncJson(url,json); //請求當前賬戶的資訊
        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); //請求當前賬戶的資訊
        return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字串序列化
    }
}