我有一个奇怪的问题,一个为我制作的函数在许多情况下都能完美运行,但是在一个地址(我不能说是为了保密)总是返回一个错误 401。在浏览器中,这个地址工作正常,但使用 HttpWebRequest不。有关更多信息,服务器使用 SSL 和 SAP 运行。接下来的功能是:
public static HttpWebResponse MakeRequest(string uri, string method, Dictionary<string, string> postData, CookieContainer cookies, ICredentials credentials, WebProxy proxy)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.CookieContainer = (cookies != null) ? cookies : new CookieContainer();
webRequest.AllowAutoRedirect = true;
webRequest.Credentials = (credentials != null) ? credentials : CredentialCache.DefaultCredentials;
webRequest.Method = method.ToUpper();
webRequest.Headers.Add("HTTP_USER_AGENT", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1134.0 Safari/537.1");
webRequest.Headers.Add("HTTP_ACCEPT", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
webRequest.Headers.Add("HTTP_ACCEPT_ENCODING", "gzip,deflate");
webRequest.Headers.Add("HTTP_ACCEPT_LANGUAGE", "es-ES,es;q=0.8");
webRequest.Headers.Add("HTTP_ACCEPT_CHARSET", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(
ValidateRemoteCertificate
);
if (proxy != null)
{
webRequest.Proxy = proxy;
}
if (method.ToLower() == "post" && postData != null)
{
StringBuilder sb = new StringBuilder();
foreach (string key in postData.Keys)
{
sb.AppendFormat("{0}={1}&", key, Text.UrlEncode(postData[key].ToString()));
}
if (sb.Length > 0)
{
string finalString = sb.ToString();
Text.Chop(ref finalString);
byte[] bytedata = Encoding.ASCII.GetBytes(finalString);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = bytedata.Length;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
}
}
try
{
return (HttpWebResponse)webRequest.GetResponse();
}
finally
{
}
}
非常感谢。