C#中通过HttpClient发送Post请求

2023-05-16

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

微软文档地址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();
        }
 

在阿里云上的.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;

/// <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, 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">请求对象数据</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);//把收到的字符串序列化
    }
}
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<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();
 
        }
    }
}
 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C#中通过HttpClient发送Post请求 的相关文章

随机推荐

  • C#中进程间通信方式汇总

    一 进程间通讯的方式 进程间通讯的方式有很多 xff0c 常用的有共享内存 xff08 内存映射文件 共享内存DLL 剪切板等 xff09 命名管道和匿名管道 发送消息等几种方法来直接完成 xff0c 另外还可以通过socket口 配置文件
  • ubuntu shared folder to windows

    一 安装smb 执行命令行 xff1a sudo apt get install samba sudo apt get install smbfs 二 添加准备共享的文件夹 有如下三种配置共享文件夹的方法 xff0c 任选一种方法即可 xf
  • C# 获得窗体句柄并发送消息(利用windows API可在不同进程中获取)

    C 使用Windows API获取窗口句柄控制其他程序窗口 编写程序模拟鼠标和键盘操作可以方便的实现你需要的功能 xff0c 而不需要对方程序为你开放接口 比如 xff0c 操作飞信定时发送短信等 我之前开发过飞信耗子 xff0c 用的是对
  • c#中mysql远程连接方法及实例

    region 远程数据库连接测试 需给远程数据库分配所有权限 cmd命令 xff1a grant all privileges on to 39 root 39 64 39 39 with grant option string connS
  • mysql中数据库覆盖导入的几种方式

    众所周知 xff0c 数据库中INSERT INTO语法是append方式的插入 xff0c 而最近在处理一些客户数据导入场景时 xff0c 经常遇到需要覆盖式导入的情况 xff0c 常见的覆盖式导入主要有下面两种 xff1a 1 部分覆盖
  • mysql并发写入性能分析

    目前 xff0c 在很多OLTP场景中 xff0c MySQL数据库都有着广泛的应用 xff0c 也有很多不同的使用方式 从数据库的业务需求 架构设计 运营维护 再到扩容迁移 xff0c 不同的MySQL架构有不同的特点 xff0c 适应一
  • c#中的DefWndProc是Control类的虚函数

    protected override void DefWndProc ref Message m protected override void DefWndProc ref Message m 是Control的虚函数
  • C#使用Win32API获得窗口和控件的句柄

    整个Windows编程的基础 一个句柄是指使用的一个唯一的整数值 即一个4字节 64位程序中为8字节 长的数值 来标识应用程序中的不同对象和同类中的不同的实例 诸如 一个窗口 按钮 图标 滚动条 输出设备 控件或者文件等 应用程序能够通过句
  • C/C++新建注册表项实例

    使用Windows API 函数中的RegCreateKeyEx函数来实现对注册表新建注册表项 RegCreateKeyEx函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 原形 LONG RegCreateKeyEx
  • c#中通过win32API(FindWindowEx)查找控件句柄实例

    函数功能 该函数获得一个窗口的句柄 该窗口的类名和窗口名与给定的字符串相匹配 这个函数查找子窗口 从排在给定的子窗口后面的下 一个子窗口开始 在查找时不区分大小写 函数原型 HWND FindWindowEx HWND hwndParent
  • c#中使用消息循环机制发送接收字符串的方法和数据类型转换

    在定义消息时忘记了用户可定义消息的边界值 xff0c 在网上一阵疯找后来发现是const int WM USER 61 0x400 接着是SendMessage的lParam类型不能决定 xff08 默认是IntPtr xff09 xff0
  • C#WebApi路由机制详解

    随着前后端分离的大热 WebApi在项目中的作用也是越来越重要 可单独部署 与前端和App交互都很方便 既然有良好的发展趋势 我们当然应该顺势而为 搞懂WebApi Restful相当于给Http请求增加了语义 Post 增 Delete
  • xubuntu(ubuntu)重启后不能进入图形化界面

    问题描述 xff1a Xbuntu启动后进入了 VMware Easy Install视图 xff0c 不能进入图形化界面 问题思路 xff1a 在命令行模式下命令联想敲击时会报硬盘容量不足 xff0c 怀疑可能和硬盘大小相关 先尝试清理下
  • JSON数据格式详解

    文章目录 JSON数据格式概念 JSON的简单数据 JSON对象 对象的属性也可以是JSON对象 JSON格式表示简单数组 对象数组 使用二维数组保存 二维数组 访问淘宝的接口也可以取得JSON格式的数据 将一个对象转换成JSON数据 将一
  • C# 创建一个简单的WebApi项目

    一 创建Web API 1 创建一个新的web API项目 启动VS 2013 并在 开始页 选择 新项目 或从 文件 菜单选择 新建 然后选择 项目 在 模板 面板中选择 已安装模板 并展开 Visual C 节点 选择该节点下的 Web
  • C# 编写Web API

    1 创建Web API项目 打开VS2012 gt FILE gt New gt Project gt Web gt ASP NET MVC 4 Web Application 修改名字为WebAPIApplication 单击OK 在Pr
  • C# WebApi 返回JSON类型

    在默认情况下 当我们新建一个webapi项目 会自动返回XML格式的数据 如果我们想返回JSON的数据 可以设置下面的三种方法 nbsp 1 不用改配置文件 在Controller的方法中 直接返回HttpResponseMessage p
  • c#通过HttpClient来调用Web Api接口

    lt summary gt HttpClient实现Post请求 异步 lt summary gt static async void dooPost string url http localhost 52824 api register
  • c#使用HttpClient调用WebApi

    调用WebApi 可以利用HttpClient来进行Web Api的调用 由于WebA Api的调用本质上就是一次普通的发送请求与接收响应的过程 xff0c 所有HttpClient其实可以作为一般意义上发送HTTP请求的工具 using
  • C#中通过HttpClient发送Post请求

    C 中HttpClient进行各种类型的传输 我们可以看到 尽管PostAsync有四个重载函数 但是接受的都是HttpContent 而查看源码可以看到 HttpContent是一个抽象类 那我们就不可能直接创建HttpContent的实