LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C#使用HttpClient四种请求数据格式:json、表单数据、文件上传、xml格式

admin
2024年6月8日 18:15 本文热度 504

前言

当下编写应用程序都流行前后端分离,后端提供对应服务接口给前端或跨应用程序调用,如WebAPI等。在调用这些服务接口发送HTTP请求,而.NET为我们提供了HttpWebRequest、HttpClient几个类库来实现。下面对C#使用HttpClient类发送HTTP请求数据的几种格式。

HttpClient

HttpClient是.NET 4.5以上版提供的类(System.Net.Http),编写的应用程序可以通过此类发送HTTP请求并从WEB服务公开的资源接收HTTP响应。HTTP请求包含了请求报文与响应报文。下面先简单的了解它的一些属性与方法。
属性:
属性描述
BaseAddress获取或设置发送请求时地址。
DefaultProxy获取或设置全局HTTP请求代理。
DefaultRequestHeaders获取请求发送的标题。
DefaultRequestVersion获取或设置请求使用的默认HTTP版本。
MaxResponseContentBufferSize获取或设置读取响应内容时要缓冲的最大字节数。
Timeout获取或设置请求超时等待的时间。
方法:
方法描述
GetAsync异步请求获取指定URI。
GetByteArrayAsync异步请求获取指定URI并以字节数组的形式返回响应。
GetStreamAsync异步请求获取指定URI并以流的形式返回响应。
GetStringAsync异步请求获取指定URI并以字符串的形式返回响应正文。
PostAsync异步将POST请求发送给指定URI。
Send发送带有指定请求的 HTTP 请求。
SendAsync以异步操作发送 HTTP 请求。

数据格式

在向HTTP发起请求时,将以什么样的数据格式发送数据,这取决于URI服务资源。而常用的类型可分为application/json、application/x-www-form-urlencoded, multipart/form-data, text/xml,其中application/json 是近年来最常用的一种。下面简单介绍每种格式。

JSON数据格式

application/json 通常是HttpClient发送JSON格式的数据,通过使用HttpContent的StringContent并设置其MediaType为"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{    internal class Program    {        static async Task Main(string[] args)        {            try            {                using (HttpClient httpClient = new HttpClient())                {                    User user = new User();                    user.username = "test";                    user.password = "123456";                    string jsonData = JsonConvert.SerializeObject(user);                    // 发送请求数据包                    StringContent content = new StringContent(jsonData, Encoding.UTF8);                    // 设置HTTP 响应上的ContentType --application/json                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");                    // 请求访问地址                    string url = "https://127.0.0.1/api/user/login";                    // 发出HTTP的Post请求                    HttpResponseMessage response = await httpClient.PostAsync(url, content);                    // 读取返回结果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 将字符转对象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

表单数据格式

application/x-www-form-urlencoded 这种格式通常用于表单数据的提交,通过使用HttpContent的FormUrlEncodedContent 类定义实现。
示例:
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;
namespace Fountain.WinConsole.HttpDemo{    internal class Program    {        static async Task Main(string[] args)        {            try            {                using (HttpClient httpClient = new HttpClient())                {                    Dictionary<string,string> user = new Dictionary<string, string>                    {                        { "username", "test" },                        { "password", "123456" }                    };                    // 发送请求数据包                    FormUrlEncodedContent content = new FormUrlEncodedContent(user);                    // 请求访问地址                    string url = "https://127.0.0.1/api/user/login";                    // 发出HTTP的Post请求                    HttpResponseMessage response = await httpClient.PostAsync(url, content);                    // 读取返回结果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 将字符转对象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

文件上传格式

multipart/form-data 常用于文件上传的数据格式,通过用MultipartFormDataContent类定义实现。
示例:
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;
namespace Fountain.WinConsole.HttpDemo{    internal class Program    {        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");                    // 请求访问地址                    string url = "https://127.0.0.1/api/user/upload";                    // 发出HTTP的Post请求                    HttpResponseMessage response = await httpClient.PostAsync(url, multipartContent);                    // 读取返回结果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 将字符转对象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

XML数据格式

text/xml 主要用于传输XML格式的数据,通过使用HttpContent 中的StringContent并设置其MediaType为"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;
namespace Fountain.WinConsole.HttpDemo{    internal class Program    {        static async Task Main(string[] args)        {            try            {                using (HttpClient httpClient = new HttpClient())                {                    StringBuilder user = new StringBuilder();                    user.AppendLine("<usrname>test</usrname>");                    user.AppendLine("<password>test123456</password>");                    string xmlData = user.ToString();                    // 发送请求数据包                    StringContent content = new StringContent(xmlData, Encoding.UTF8);                    // 设置HTTP 响应上的ContentType --text/xml                    content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");                    // 请求访问地址                    string url = "https://127.0.0.1/api/user/login";                    // 发出HTTP的Post请求                    HttpResponseMessage response = await httpClient.PostAsync(url, content);                    // 读取返回结果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 将字符转对象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

小结

以上是C#在使用HttpClient类发起 HTTP 的Post请求时,使用四种数据格式的方式。希望对各位有所帮助。如有不到之处,请多多包涵。


该文章在 2024/6/8 18:15:51 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved