使用以下代码调用SOAP时,我得到的是#34; Unauthorized"作为回应。
NetworkCredential credentials = new NetworkCredential("username", "password");
var request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = credentials;
try
{
WebResponse response = request.GetResponse();
using(Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch(WebException Ex)
{
WebResponse errorResponse = Ex.Response;
using(Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string errorText = reader.ReadToEnd();
}
throw;
}
你可以在我错的地方纠正我吗?
我收到错误: - "远程服务器返回错误:(401)未经授权。"
答案 0 :(得分:0)
这应该有效
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
string authInfo = "username" + ":" + "Password";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers[HttpRequestHeader.Authorization] = "Basic " + authInfo;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (var responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
答案 1 :(得分:0)
这不是错误。这是关于您的凭证的警告。您应该发送合法用户凭证以获得对您的终点的响应。请退房;
NetworkCredential credentials = new NetworkCredential{
Username=//fill your username,
Password=//fill your password but be carefull, is it hashed or not?
};
var request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = credentials;
try
{
WebResponse response = request.GetResponse();
using(Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch(WebException Ex)
{
WebResponse errorResponse = Ex.Response;
using(Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string errorText = reader.ReadToEnd();
}
throw;
}