多くの状況で完全に動作する私のために作られた関数に奇妙な問題がありますが、アドレス (機密性のために言うことはできません) では常にエラー 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
{
}
}
どうもありがとうございました。