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

9,444次阅读
没有评论

共计 6062 个字符,预计需要花费 16 分钟才能阅读完成。

前言

当下编写应用程序都流行前后端分离,后端提供对应服务接口给前端或跨应用程序调用,如 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(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 user = new Dictionary                    {                        {"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(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(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("test");                    user.AppendLine("test123456");                    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(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

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

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于2024-09-28发表,共计6062字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)