我有一个奇怪的问题,一个为我做的功能在很多情况下运行完美,但在一个地址(我不能说保密)返回总是一个错误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
{
}
}
非常感谢。
答案 0 :(得分:0)
401表示您有授权问题。鉴于您在请求中设置凭据,我猜这些不正确。例如,可能是Authentication字段的值与您在代码中使用的值相比更可接受。一种方法是,您可以调试问题的方法是在浏览器中(即工作时)检查请求标题中的内容。您可以通过多种方式验证标题,即Firefox和Firebug插件来检查标题,或者您可以使用wireshark。