本篇文章记录一下,.net 再发送请求时出现远程服务器返回错误: (418)。的解决方案。
首先我不知道出现这个问题的原因是什么,猜测可能跟对方服务器有关。
直接说我的解决方案吧。
.net 发起http请求有三种
HttpWebRequest、WebClient、HttpClient
我用的HttpWebRequest然后出现在了上述418错误,然后我改成HttpClient就可以了。
我查询了他们之间的区别,还是不知道为什么会导致此错误,所有特此记录一下
下面是HttpClient的代码,
using System.Net.Http;
/// <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, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null) { postData = 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; var result = response.Content.ReadAsStringAsync().Result; return result; } } }