C#中HTTP请求失败及问题处理方案记录
- 先上一段代码
string responseString = string.Empty;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Post";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 60 * 1000 * 5;
request.Headers.Add("Accept-Encoding", "identity");
string paramsData = ParseToString(dic);
byte[] buffer = Encoding.UTF8.GetBytes(paramsData);
request.ContentLength = buffer.Length;
using (Stream writer = request.GetRequestStream())
{
writer.Write(buffer, 0, buffer.Length);
}
AsyncCallback callback = new AsyncCallback(state =>
{
var asyncrequest = state.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(state);
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
responseString = reader.ReadToEnd();
}
});
IAsyncResult result = request.BeginGetResponse(callback, request);
return responseString;
- ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;// 4.0环境下https请求设置,否则会报请求被中止: 未能创建 SSL/TLS 安全通道。
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;环境4.5以上的写法
- request.Headers.Add(“Accept-Encoding”, “identity”);//强行要求服务器不压缩, 当你请求发现返回的数据长度response.ContentLength = -1,这会就要注意可能是服务器对下发的数据进行了压缩,如果你不设置会收到一串乱码或进行数据解压缩。
- HttpUtility.UrlEncode(app_key); 特别的说明这个是因为我请求别人的接口一直返回密钥错误,但是我密钥是正确的,但是我发现密钥中有个斜杠。用POSTMAN请求就是正确返回的,我直接请求就报错误。后面才这样设置后才能正确返回。