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();
        }
    }
}


目录
相关文章
|
XML JSON API
淘宝商品详情API的调用流程(python请求示例以及json数据示例返回参考)
JSON数据示例:需要提供一个结构化的示例,展示商品详情可能包含的字段,如商品标题、价格、库存、描述、图片链接、卖家信息等。考虑到稳定性,示例应基于淘宝开放平台的标准响应格式。
|
11月前
|
JSON 前端开发 应用服务中间件
配置Nginx根据IP地址进行流量限制以及返回JSON格式数据的方案
最后,记得在任何生产环境部署之前,进行透彻测试以确保一切运转如预期。遵循这些战术,守卫你的网络城堡不再是难题。
429 3
|
JSON 人工智能 算法
探索大型语言模型LLM推理全阶段的JSON格式输出限制方法
本篇文章详细讨论了如何确保大型语言模型(LLMs)输出结构化的JSON格式,这对于提高数据处理的自动化程度和系统的互操作性至关重要。
2262 48
|
JSON 前端开发 搜索推荐
关于商品详情 API 接口 JSON 格式返回数据解析的示例
本文介绍商品详情API接口返回的JSON数据解析。最外层为`product`对象,包含商品基本信息(如id、name、price)、分类信息(category)、图片(images)、属性(attributes)、用户评价(reviews)、库存(stock)和卖家信息(seller)。每个字段详细描述了商品的不同方面,帮助开发者准确提取和展示数据。具体结构和字段含义需结合实际业务需求和API文档理解。
|
JSON Java 数据格式
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
365 25
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
|
JSON 人工智能 算法
探索LLM推理全阶段的JSON格式输出限制方法
文章详细讨论了如何确保大型语言模型(LLMs)输出结构化的JSON格式,这对于提高数据处理的自动化程度和系统的互操作性至关重要。
3427 52
|
JSON JavaScript Java
对比JSON和Hessian2的序列化格式
通过以上对比分析,希望能够帮助开发者在不同场景下选择最适合的序列化格式,提高系统的整体性能和可维护性。
591 3
|
JSON API 数据安全/隐私保护
拍立淘按图搜索API接口返回数据的JSON格式示例
拍立淘按图搜索API接口允许用户通过上传图片来搜索相似的商品,该接口返回的通常是一个JSON格式的响应,其中包含了与上传图片相似的商品信息。以下是一个基于淘宝平台的拍立淘按图搜索API接口返回数据的JSON格式示例,同时提供对其关键字段的解释
|
JSON 数据格式 索引
Python中序列化/反序列化JSON格式的数据
【11月更文挑战第4天】本文介绍了 Python 中使用 `json` 模块进行序列化和反序列化的操作。序列化是指将 Python 对象(如字典、列表)转换为 JSON 字符串,主要使用 `json.dumps` 方法。示例包括基本的字典和列表序列化,以及自定义类的序列化。反序列化则是将 JSON 字符串转换回 Python 对象,使用 `json.loads` 方法。文中还提供了具体的代码示例,展示了如何处理不同类型的 Python 对象。
792 1
|
JSON Java 数据格式
springboot中表字段映射中设置JSON格式字段映射
springboot中表字段映射中设置JSON格式字段映射
742 1