溫馨提示×

c# httpwebrequest怎樣處理身份驗證

c#
小樊
81
2024-11-16 20:47:56
欄目: 編程語言

在C#中,使用HttpWebRequest處理身份驗證的常見方法有兩種:基本身份驗證(Basic Authentication)和摘要式身份驗證(Digest Authentication)。下面是這兩種方法的示例代碼。

  1. 基本身份驗證(Basic Authentication):
using System;
using System.IO;
using System.Net;
using System.Text;

class Program
{
    static void Main()
    {
        string url = "https://example.com/api/resource";
        string username = "your_username";
        string password = "your_password";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.Credentials = new NetworkCredential(username, password);
        request.PreAuthenticate = true;

        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string responseText = reader.ReadToEnd();
                    Console.WriteLine(responseText);
                }
            }
        }
        catch (WebException ex)
        {
            using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response)
            {
                Console.WriteLine("Error code: {0}", errorResponse.StatusCode);
            }
        }
    }
}
  1. 摘要式身份驗證(Digest Authentication):
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main()
    {
        string url = "https://example.com/api/resource";
        string username = "your_username";
        string password = "your_password";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.Credentials = new NetworkCredential(username, password);
        request.PreAuthenticate = true;

        // Create the digest authentication header
        string authHeader = CreateDigestAuthHeader(username, password, url);
        request.Headers["Authorization"] = authHeader;

        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string responseText = reader.ReadToEnd();
                    Console.WriteLine(responseText);
                }
            }
        }
        catch (WebException ex)
        {
            using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response)
            {
                Console.WriteLine("Error code: {0}", errorResponse.StatusCode);
            }
        }
    }

    static string CreateDigestAuthHeader(string username, string password, string url)
    {
        byte[] credentials = Encoding.ASCII.GetBytes(username + ":" + password);
        using (HMACSHA256 hmac = new HMACSHA256(credentials))
        {
            byte[] hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(url));
            StringBuilder authHeader = new StringBuilder();
            authHeader.Append("Digest username=\"");
            authHeader.Append(username);
            authHeader.Append("\", realm=\"example.com\", uri=\"");
            authHeader.Append(url);
            authHeader.Append("\", response=\"");
            authHeader.Append(Convert.ToBase64String(hash));
            authHeader.Append("\"");
            return authHeader.ToString();
        }
    }
}

請注意,這些示例代碼可能需要根據(jù)您的實際需求進(jìn)行調(diào)整。在實際應(yīng)用中,您可能需要處理異常、設(shè)置請求頭、處理響應(yīng)等。

0