Xamarin.Forms如何以application/x-www-form-urlencoded格式向API发送数据
解决方案:C# 发送 x-www-form-urlencoded 格式请求的实现方案
x-www-form-urlencoded 是键值对拼接的表单格式,不需要使用 Newtonsoft.Json 做序列化,你可以按以下两种常用方案实现:
方案1:使用 HttpClient 原生实现(推荐)
该方法无需手动处理编码和请求头设置,官方类会自动适配格式要求:
- 先构造键值对集合,填入你需要提交的请求参数
- 用
FormUrlEncodedContent封装参数集合 - 直接调用
PostAsync发送请求即可
using System.Net.Http; using System.Collections.Generic; // 注意:实际项目中请全局复用HttpClient实例,不要每次请求都新建,避免套接字资源耗尽 var httpClient = new HttpClient(); // 构造请求参数 var formData = new Dictionary<string, string> { { "username", "test_user" }, { "password", "test_pass" }, { "custom_param", "custom_value" } }; // 自动封装为x-www-form-urlencoded格式的请求内容 var content = new FormUrlEncodedContent(formData); // 发送POST请求 var response = await httpClient.PostAsync("你的API接口地址", content); // 读取返回结果 var responseStr = await response.Content.ReadAsStringAsync();
方案2:手动构造请求(适用于需要精细控制的场景)
如果有特殊自定义需求,可手动拼接参数,注意所有键和值都需要做URL编码,避免特殊字符导致请求异常:
using System.Net.Http; using System.Web; var httpClient = new HttpClient(); // 手动拼接表单参数,用HttpUtility.UrlEncode做URL编码 var param1 = HttpUtility.UrlEncode("param1") + "=" + HttpUtility.UrlEncode("参数1的特殊值&=#@"); var param2 = HttpUtility.UrlEncode("param2") + "=" + HttpUtility.UrlEncode("参数2的值"); var formContent = new StringContent($"{param1}&{param2}", System.Text.Encoding.UTF8, "application/x-www-form-urlencoded"); // 发送请求 var response = await httpClient.PostAsync("你的API接口地址", formContent);
注意事项
- 不要使用 Newtonsoft.Json 对参数做序列化,x-www-form-urlencoded 是
key1=value1&key2=value2的格式,和JSON结构完全不同 FormUrlEncodedContent会自动设置Content-Type请求头为application/x-www-form-urlencoded,不需要手动添加- 生产环境建议通过依赖注入注入全局
HttpClient实例,或者用静态变量复用,不要每次请求新建实例
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

