【发布时间】:2011-09-01 05:43:29
【问题描述】:
我正在尝试通过 HTTP Post 发送一些 XML。但我收到401 Unauthorized。有趣的是,当我通过浏览器访问 URL 时,我提供的用户名/密码都可以。
这是我的方法签名:
internal static string Send(string URL, string XMLdata, string RequestMethod,
string RequestUsername, string RequestPassword)
我已经尝试过这个作为方法体:
string requestData = XMLdata;
string responseData = "";
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(URL);
objRequest.Method = RequestMethod;
objRequest.PreAuthenticate = true;
objRequest.ContentType = "application/x-www-form-urlencoded";//"text/xml";
objRequest.Credentials = new NetworkCredential(RequestUsername, RequestPassword);;
objRequest.ContentLength = requestData.Length;
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(requestData);
}
finally
{
myWriter.Close();
}
StreamReader sr = null;
try
{
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
sr = new StreamReader(objResponse.GetResponseStream());
responseData = sr.ReadToEnd();
}
finally
{
if (sr != null)
sr.Close();
}
return responseData;
还有这个:
string result;
using (var client = new WebClient())
{
Uri requestUri = new Uri(URL);
CredentialCache cache = new CredentialCache();
NetworkCredential nc = new NetworkCredential(RequestUsername, RequestPassword);
cache.Add(requestUri, "Basic", nc);
client.Credentials = cache;
result = client.UploadString(requestUri, XMLdata);
}
return result;
两者都获得401。我究竟做错了什么?提醒一下:当我通过浏览器访问 URL 时,它会提示输入用户名/密码,并且我提供的凭据是可以的。
到目前为止我对该主题的阅读:
- HttpClient and forms authentication in C#
- Login to the page with HttpWebRequest
- HTTP POST Returns Error: 417 "Expectation Failed."
- HTTP Post XML document - server receives only first line
- POST to HTTPS authentication error
- C# Xml in Http Post Request Message Body
感谢您的帮助。
【问题讨论】:
-
可能认证类型是NTLM?
-
根据您的描述,我没有给您答案,但我有一个建议:使用 Fiddler 查看请求和响应的样子,无论是浏览器请求成功的时间,还是浏览器请求成功的时间编程请求失败。我怀疑会有一个不同的地方跳出来。
-
“它提示输入用户名/密码” - 在弹出窗口中?然后就是 Win auth。
-
是的,不管是什么浏览器,都会在浏览器弹窗中提示。您确定这会成为 Windows 身份验证吗?不管怎样,你知道我在发布的代码中做了什么改动吗?
-
@jwismar 很棒的提示,会告诉你结果。顺便说一句,您应该将其发布为答案
标签: c# http authentication