[英]Setting Network Credentials for Simple WebRequest
相對較新的C#,但取得了良好的進展。
我目前正在嘗試測試System.Net.WebRequest方法。 使用https://httpbin.org/上有用的http測試工具包 - 我正在嘗試將網絡憑據傳遞給https://httpbin.org/basic-auth/user/passwd並檢索成功的連接。 (目前獲得401的)
用戶名是user,密碼是passwrd。
我有一個簡單的表單,以及啟動請求的按鈕。 但是,如上所述,它不起作用,我得到401錯誤。
這是我到目前為止:
private void button1_Click(object sender, EventArgs e)
{
NetworkCredential myCred = new NetworkCredential(
"user", "passwrd", "https://httpbin.org");
// Create a request for the URL.
WebRequest request = WebRequest.Create(
"https://httpbin.org/basic-auth/user/passwd");
// If required by the server, set the credentials.
request.Credentials = myCred;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams and the response.
reader.Close();
response.Close();
}
問題在於您的憑據,您假設該domain
是HTTP域,但這僅對Active Directory域之類的內容有用。 只需刪除該參數(並修復密碼),它就會起作用:
NetworkCredential myCred = new NetworkCredential("user", "passwd");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.