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