通常情况下都是使用 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 = 0; 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(); }