为简单WebRequest设置网络凭据

时间:2016-07-12 10:19:45

标签: c# https

相对较新的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();
    }

1 个答案:

答案 0 :(得分:3)

问题在于您的凭据,您假设domain是HTTP域,但这仅对Active Directory域之类的内容有用。只需删除该参数(并修复密码),它就会起作用:

NetworkCredential myCred = new NetworkCredential("user", "passwd");