C#中通过HttpClient发送Post请求

C#中HttpClient进行各种类型的传输

我们可以看到, 尽管PostAsync有四个重载函数, 但是接受的都是HttpContent, 而查看源码可以看到, HttpContent是一个抽象类

那我们就不可能直接创建HttpContent的实例, 而需要去找他的实现类, 经过一番研究, 发现了, 如下四个:

MultipartFormDataContent、FormUrlEncodedContent、StringContent、StreamContent

和上面的总结进行一个对比就能发现端倪:

MultipartFormDataContent=》multipart/form-data

FormUrlEncodedContent=》application/x-www-form-urlencoded

StringContent=》application/json等

StreamContent=》binary

而和上面总结的一样FormUrlEncodedContent只是一个特殊的StringContent罢了, 唯一不同的就是在mediaType之前自己手动进行一下URL编码罢了(这一条纯属猜测, 逻辑上应该是没有问题的).

c# 使用HttpClient的post,get方法传输json

————————————————

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

自己封装的类,我几乎所有的个人项目都用这个
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;

/// 
/// 基于HttpClient封装的请求类
/// 
public class HttpRequest
{
    /// 
    /// 使用post方法异步请求
    /// 
    /// 目标链接
    /// 发送的参数字符串,只能用json
    /// 返回的字符串
    public static async Task 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;
    }

    /// 
    /// 使用post方法异步请求
    /// 
    /// 目标链接
    /// 发送的参数字符串
    /// 返回的字符串
    public static async Task PostAsync(string url, string data, Dictionary 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;
    }

    /// 
    /// 使用get方法异步请求
    /// 
    /// 目标链接
    /// 返回的字符串
    public static async Task GetAsync(string url, Dictionary 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;
    }

    /// 
    /// 使用post返回异步请求直接返回对象
    /// 
    /// 返回对象类型
    /// 请求对象类型
    /// 请求链接
    /// 请求对象数据
    /// 请求返回的目标对象
    public static async Task PostObjectAsync(string url, T2 obj)
    {
        String json = JsonConvert.SerializeObject(obj);
        string responseBody = await PostAsyncJson(url, json); //请求当前账户的信息
        return JsonConvert.DeserializeObject(responseBody);//把收到的字符串序列化
    }

    /// 
    /// 使用Get返回异步请求直接返回对象
    /// 
    /// 请求对象类型
    /// 请求链接
    /// 返回请求的对象
    public static async Task GetObjectAsync(string url)
    {
        string responseBody = await GetAsync(url); //请求当前账户的信息
        return JsonConvert.DeserializeObject(responseBody);//把收到的字符串序列化
    }
}
————————————————
版权声明:本文为CSDN博主「luckyone906」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011555996/article/details/116721769

C# 使用 HttpClient 进行http GET/POST请求

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 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> param = new List>();
            param.Add(new KeyValuePair("xx", "xx"));
           Task responseMessage  =httpClient0.PostAsync("http://localhost:1083/Home/Test", new FormUrlEncodedContent(param));
            responseMessage.Wait();
           Task reString= responseMessage.Result.Content.ReadAsStringAsync();
            reString.Wait();
            Console.WriteLine(reString.Result);
            Console.ReadLine();
 
        }
    }
}
————————————————
版权声明:本文为CSDN博主「luckyone906」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011555996/article/details/116721769

你可能感兴趣的:(WebApi,网络协议,网络)