簡體   English   中英

將XML發布到REST時發生HTTP 401錯誤

[英]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);

有幾件事要嘗試:

  • 更改內容類型,因為您沒有將json發布到它
  • 不將數據編碼為期望的xml,而不是二進制流

希望這可以幫助。

使用Fiddler並查看從服務器返回的WWW-Authenticate標頭。 這將告訴您服務器支持哪種身份驗證方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM