简体   繁体   中英

Setting Network Credentials for Simple WebRequest

Relatively new to C#, but making good progress.

I'm currently trying to test a System.Net.WebRequest method. Using the useful http testing kit at https://httpbin.org/ - I am trying to pass network credentials to https://httpbin.org/basic-auth/user/passwd and to retrieve a successful connection. (Currently getting 401's)

The username is user, and the password is passwrd.

I have a simple form, and button which starts the request. However, as stated, its not working, and i'm getting a 401 error.

Here is what I have so far:

        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();
    }

The problem is with your credentials, you are assuming that domain is the HTTP domain, but that's only useful for something like Active Directory domains. Just remove that parameter (and fix the password) and it will work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM