我正在尝试将XML发布到REST服务。这是我正在使用的代码:
我在调用服务时遇到以下错误。
远程服务器返回错误:(401)未经授权。
我也尝试过直接设置NetworkCredentials,即
NetworkCredential nc = new NetworkCredential(username, password);
serviceRequest.Credentials = nc;
感谢您的帮助。
Uri address = new Uri("https://localhost:30000/restservice/");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";
string data = @"<Sample XML Here>";
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(address, "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Response.Write(reader.ReadToEnd());
}
答案 0 :(得分:0)
要尝试的事情:
希望这有帮助。
答案 1 :(得分:0)
使用Fiddler并查看从服务器返回的WWW-Authenticate标头。这将告诉您服务器支持哪种身份验证方案。
答案 2 :(得分:0)
尝试在此请求中设置凭据
request.Credentials = new NetworkCredential(username, password);