在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();
}
}
}
请注意,这些示例代码可能需要根据您的实际需求进行调整。在实际应用中,您可能需要处理异常、设置请求头、处理响应等。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: c#中怎么操作sqlite数据库