我使用此方法执行POST请求:
public static string GetHttp(string url, Dictionary<string, string> query)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
foreach(var e in query)
{
outgoingQueryString.Add(e.Key, e.Value);
}
string postData = outgoingQueryString.ToString();
request.Method = "POST";
var data = Encoding.ASCII.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var sp = request.ServicePoint;
var prop = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
prop.SetValue(sp, (byte)0, null);
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
return Encoding.ASCII.GetString(
Encoding.Convert(
Encoding.UTF8,
Encoding.GetEncoding(
Encoding.ASCII.EncodingName,
new EncoderReplacementFallback(string.Empty),
new DecoderExceptionFallback()
),
Encoding.UTF8.GetBytes(responseString)
));
}
}
此代码几乎在所有网址上都能正常工作,但在某些网站上,只有在azure上,有时我会收到超时错误。如果请求是通过WebClient而不是HttpWebRequest执行的,我会收到此错误:
[SocketException(0x274c):连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应xx.xx.xxx.xxx:80] System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,SocketAddress socketAddress)+395 System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,Socket s4,Socket s6,Socket&amp; socket,IPAddress&amp; address,ConnectSocketState state,IAsyncResult asyncResult,Exception&amp; exception)+515
[WebException:无法连接到远程服务器] System.Net.HttpWebRequest.GetRequestStream(TransportContext&amp; context)+58935447
我尝试配置保持连接但这并不能解决问题:
request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version11;
request.ServicePoint.ConnectionLimit = 12;
request.Proxy = null;
request.Timeout = 240000;
request.AllowAutoRedirect = false;
request.Credentials = CredentialCache.DefaultCredentials;
request.Accept = "*/*";
ServicePointManager.SetTcpKeepAlive(true, 240000, 240000);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };