[英]HTTP 401 Error while posting XML to REST
我正在嘗試將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());
}
嘗試在這樣的請求中設置憑據
request.Credentials = new NetworkCredential(username, password);
有幾件事要嘗試:
希望這可以幫助。
使用Fiddler並查看從服務器返回的WWW-Authenticate標頭。 這將告訴您服務器支持哪種身份驗證方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.