我对C#比较新,但进展顺利。
我目前正在尝试测试一个System.Net.WebRequest方法。使用有用的http测试工具https://httpbin.org/ - 我正在尝试传递网络凭据到https://httpbin.org/basic-auth/user/passwd并检索成功的连接。(目前收到401错误)
用户名为user,密码为passwd。
我有一个简单的表单和按钮来启动请求。然而,正如所述,它没有起作用,我得到了一个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();
}
passwd
而不是passwrd
。 - SimpleVarNetworkCredentials
。同时尝试req.CachePolicy = new..(NoCacheNoStore);
确保您确实从之前的尝试中获得了非缓存响应。 - SimpleVar