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

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

前言

当下编写应用程序都流行前后端分离,后端提供对应服务接口给前端或跨应用程序调用,如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#一分钟浅谈:文件上传与下载功能实现
【10月更文挑战第2天】在Web应用开发中,文件的上传与下载是常见需求。本文从基础入手,详细讲解如何在C#环境下实现文件上传与下载。首先介绍前端表单设计及后端接收保存方法,使用`&lt;input type=&quot;file&quot;&gt;`与`IFormFile`接口;接着探讨错误处理与优化策略,如安全性验证和路径管理;最后讲解文件下载的基本步骤,包括确定文件位置、设置响应头及发送文件流。此外,还提供了进阶技巧,如并发处理、大文件分块上传及进度监控,帮助开发者构建更健壮的应用系统。
1096 16
|
XML JSON Java
使用IDEA+Maven搭建整合一个Struts2+Spring4+Hibernate4项目,混合使用传统Xml与@注解,返回JSP视图或JSON数据,快来给你的SSH老项目翻新一下吧
本文介绍了如何使用IntelliJ IDEA和Maven搭建一个整合了Struts2、Spring4、Hibernate4的J2EE项目,并配置了项目目录结构、web.xml、welcome.jsp以及多个JSP页面,用于刷新和学习传统的SSH框架。
651 0
使用IDEA+Maven搭建整合一个Struts2+Spring4+Hibernate4项目,混合使用传统Xml与@注解,返回JSP视图或JSON数据,快来给你的SSH老项目翻新一下吧
|
Java Spring 容器
彻底改变你的编程人生!揭秘 Spring 框架依赖注入的神奇魔力,让你的代码瞬间焕然一新!
【8月更文挑战第31天】本文介绍 Spring 框架中的依赖注入(DI),一种降低代码耦合度的设计模式。通过 Spring 的 DI 容器,开发者可专注业务逻辑而非依赖管理。文中详细解释了 DI 的基本概念及其实现方式,如构造器注入、字段注入与 setter 方法注入,并提供示例说明如何在实际项目中应用这些技术。通过 Spring 的 @Configuration 和 @Bean 注解,可轻松定义与管理应用中的组件及其依赖关系,实现更简洁、易维护的代码结构。
442 0
|
XML JSON 缓存
优化Java中XML和JSON序列化
优化Java中XML和JSON序列化
|
XML JSON 开发框架
一篇文章讲明白JSON格式转换成XML格式
一篇文章讲明白JSON格式转换成XML格式
251 0
|
XML JSON 开发框架
一篇文章讲明白JSON格式转换成XML格式
一篇文章讲明白JSON格式转换成XML格式
300 0
|
10月前
|
XML 前端开发 C#
C#编程实践:解析HTML文档并执行元素匹配
通过上述步骤,可以在C#中有效地解析HTML文档并执行元素匹配。HtmlAgilityPack提供了一个强大而灵活的工具集,可以处理各种HTML解析任务。
427 19
|
C# 开发者
C# 一分钟浅谈:Code Contracts 与契约编程
【10月更文挑战第26天】本文介绍了 C# 中的 Code Contracts,这是一个强大的工具,用于通过契约编程增强代码的健壮性和可维护性。文章从基本概念入手,详细讲解了前置条件、后置条件和对象不变量的使用方法,并通过具体代码示例进行了说明。同时,文章还探讨了常见的问题和易错点,如忘记启用静态检查、过度依赖契约和性能影响,并提供了相应的解决建议。希望读者能通过本文更好地理解和应用 Code Contracts。
469 3
|
11月前
|
监控 算法 C#
C#与Halcon联合编程实现鼠标控制图像缩放、拖动及ROI绘制
C#与Halcon联合编程实现鼠标控制图像缩放、拖动及ROI绘制
2350 0
|
存储 安全 编译器
学懂C#编程:属性(Property)的概念定义及使用详解
通过深入理解和使用C#的属性,可以编写更清晰、简洁和高效的代码,为开发高质量的应用程序奠定基础。
1535 12