.net core运用application/x-www-form-urlencoded发起post请求
通常情况下都是使用 application/json发起post请求,但是有的.net 接口只接收 application/x-www-form-urlencoded
例如:
{
name:"张三",
results:[
{score:88,subject:"语文"}
]
}
需改为 name=张三&results[0][score]=88&results[0][subject]=语文方式
对常规的post请求进行处理,把json转为urlencoded
/// <summary>
/// 发起POST同步请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static string HttpPost(string url, string postData = null, Dictionary<string, string> headers = null, string contentType = "application/json", int timeOut = 30)
{
postData = postData ?? "";
if (contentType == "application/x-www-form-urlencoded")
{
postData = JsonUrlEncode(postData);
}
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
以下为json转urlencoded的方法和地柜
/// <summary>
/// json转urlencode
/// </summary>
/// <returns></returns>
public static string JsonUrlEncode(string json)
{
Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
StringBuilder builder = new StringBuilder();
foreach (KeyValuePair<string, object> item in dic)
{
builder.Append(GetFormDataContent(item, ""));
}
return builder.ToString().TrimEnd('&');
} /// <summary>
/// 递归转formdata
/// </summary>
/// <param name="item"></param>
/// <param name="preStr"></param>
/// <returns></returns>
private static string GetFormDataContent(KeyValuePair<string, object> item, string preStr)
{
StringBuilder builder = new StringBuilder();
if (string.IsNullOrEmpty(item.Value?.ToString()))
{
builder.AppendFormat("{0}={1}", string.IsNullOrEmpty(preStr) ? item.Key : (preStr + "[" + item.Key + "]"), System.Web.HttpUtility.UrlEncode((item.Value == null ? "" : item.Value.ToString()).ToString()));
builder.Append("&");
}
else
{
//如果是数组
if (item.Value.GetType().Name.Equals("JArray"))
{
var children = JsonConvert.DeserializeObject<List<object>>(item.Value.ToString());
for (int j = ; j < children.Count; j++)
{
Dictionary<string, object> childrendic = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(children[j]));
foreach (var row in childrendic)
{
builder.Append(GetFormDataContent(row, string.IsNullOrEmpty(preStr) ? (item.Key + "[" + j + "]") : (preStr + "[" + item.Key + "][" + j + "]")));
}
} }
//如果是对象
else if (item.Value.GetType().Name.Equals("JObject"))
{
Dictionary<string, object> children = JsonConvert.DeserializeObject<Dictionary<string, object>>(item.Value.ToString());
foreach (var row in children)
{
builder.Append(GetFormDataContent(row, string.IsNullOrEmpty(preStr) ? item.Key : (preStr + "[" + item.Key + "]")));
}
}
//字符串、数字等
else
{
builder.AppendFormat("{0}={1}", string.IsNullOrEmpty(preStr) ? item.Key : (preStr + "[" + item.Key + "]"), System.Web.HttpUtility.UrlEncode((item.Value == null ? "" : item.Value.ToString()).ToString()));
builder.Append("&");
}
} return builder.ToString();
}
.net core运用application/x-www-form-urlencoded发起post请求的更多相关文章
- 利用django form 模块处理post请求
在django框架中,利用 form 模块处理post请求提交的数据,可以大大提高开发效率,减小代码冗余度,提高性能 models.py 中: from django.db import models ...
- SpringMvc Json LocalDateTime 互转,form urlencoded @ModelAttribute 转换
JDK8 的LocalDate 系列日期API ,比Date 或者 Calendar 都好用很多,但是在SpringMvc 自动装配会有点小问题 会导致抛出类似异常 default message [ ...
- Core Mvc传值Query、Form、Cookies、Session、TempData、Cache
1.传值方法 使用Request的方法(1-3): 1)Query:获取链接?后面的值 如:http://localhost:55842/Home/About?name=kxy public IAct ...
- c# Application.run和form.show区别
Application.run(form):在当前线程上开始运行标准应用程序消息循环,并使指定窗体可见. form.show() :使指定窗体可见: 参照:https://blog.csdn.net/ ...
- .Net Core 3.0 关于Windows Form和WPF的全面支持
引言 ".NET 核心是开源和跨平台.您可以使用 .NET Core 在 Windows.Mac.十几个 Linux.iPhone.IoT 设备等上运行服务器应用程序! .NET 酷睿是开源 ...
- Application.Run()和Form.Show()以及Form.ShowDialog()
ShowDialog()弹出模式化的窗体 Show()弹出非模式化的窗体 模式窗体,在关闭或隐藏前无法切换到主窗体. 非模式窗体,变换焦点使不必关闭窗体 总结:显示重要的信息,还是用模式窗体,如删除文 ...
- 在.NET Core console application中使用User Secrets(用户机密)
微软很坑地只在Microsoft.NET.Sdk.Web中提供了VS项目右键菜单的"管理用户机密"/"Manage User Secrets"菜单项,在使用Mi ...
- form表单发送请求实例
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncodi ...
- VUE axios 发送 Form Data 格式数据请求
axios 默认是 Payload 格式数据请求,但有时候后端接收参数要求必须是 Form Data 格式的,所以我们就得进行转换.Payload 和 Form Data 的主要设置是根据请求头的 C ...
随机推荐
- 关于BFC的一些事
BFC的生成 在实现CSS的布局时,假设我们不知道BFC的话,很多地方我们生成了BFC但是不知道.在布局中,一个元素是block元素还是inline元素是必须要知道的.而BFC就是用来格式化块状元素盒 ...
- 做一个完整的Hadoop项目
1. 完整的数据流图 由同ip访问的次数: SQL查询 select ip,count(ip) from tablename Group by ip; 基于Hadoop分析 使用Hadoop分析,需 ...
- Ubuntu hadoop配置之修改主机名
1.查看主机名的方法 方法1: 在终端输入hostname 方法2: 提示符 liuhongyang@ubuntu:~$ liuhongyang:用户名 ubuntu: 主机名 ~: ...
- springboot中动态修改logback日志级别
springboot中动态修改logback日志级别 在spring boot中使用logback日志时,项目运行中,想要修改日志级别. 代码如下: import org.slf4j.Logger; ...
- Mars视频笔记——Animation
Animations的使用(1) 什么是Animations 提供了一系列的动画效果,可以应用在绝大多数控件中 Animations的分类 1 Tweened Animations 渐变动画 提供了旋 ...
- 使用DevExpress的PdfViewer实现PDF打开、预览、另存为、打印(附源码下载)
场景 Winform控件-DevExpress18下载安装注册以及在VS中使用: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/1 ...
- Winforn中DevExpress的TreeList中显示某路径下的所有目录和文件(附源码下载)
场景 Winform中DevExpress的TreeList的入门使用教程(附源码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...
- Linux 笔记 - 第五章 Linux 用户与用户组管理
博客地址:http://www.moonxy.com Linux 是一个多用户的操作系统,在日常的使用中,从安全角度考虑,应该尽量避免直接使用 root 用户登录,而使用普通用户. 1. 关于用户 u ...
- 跟我学SpringCloud | 第二十章:Spring Cloud 之 okhttp
1. 什么是 okhttp ? okhttp 是由 square 公司开源的一个 http 客户端.在 Java 平台上,Java 标准库提供了 HttpURLConnection 类来支持 HTTP ...
- 【linux】【NodeJs】Centos7安装node-v10.16.3环境
前言 Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境. Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效. https://node ...