在C#中,使用HttpWebRequest
處理身份驗證的常見方法有兩種:基本身份驗證(Basic Authentication)和摘要式身份驗證(Digest 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);
}
}
}
}
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();
}
}
}
請注意,這些示例代碼可能需要根據您的實際需求進行調整。在實際應用中,您可能需要處理異常、設置請求頭、處理響應等。