使用基本身份验证的 C# API 获取请求-服务器返回(403)禁止访问

使用基本身份验证的 C# API 获取请求-服务器返回(403)禁止访问

我正在尝试连接到 API 端点。我收到 (403) Forbidden 错误。我希望有人能帮我找出我做错的地方。这是我的代码:

using System;
using System.Net;
using System.IO;
using System.Text;                  

public class Program
{
    public static void Main()
    {
        
 
string token = "Username:Password";
byte[] pwd = System.Text.Encoding.UTF8.GetBytes(token);
String encodedPassword = Convert.ToBase64String(pwd, 0, pwd.Length, Base64FormattingOptions.None);

String PostData = ("Authorization: Basic " + encodedPassword);

    
var myUri = new Uri("http://EndPoint URL");
var myWebRequest = WebRequest.Create(myUri);
var myHttpWebRequest = (HttpWebRequest)myWebRequest;
myHttpWebRequest.PreAuthenticate = true;
myHttpWebRequest.Headers.Add("Authorization", "Basic " + encodedPassword);
myHttpWebRequest.Accept = "application/json";

var myWebResponse = myWebRequest.GetResponse();
var responseStream = myWebResponse.GetResponseStream();

var myStreamReader = new StreamReader(responseStream, Encoding.Default);
var json = myStreamReader.ReadToEnd();

responseStream.Close();
myWebResponse.Close();  
    

    }
} 

相关内容