我正在嘗試api並接收數據。我得到了API的用戶名和密碼,但當我嘗試連接時,我得到了未經授權的請求。我的東西是錯誤的,我的請求頭-authentication。 這裏是我的代碼:無法使用正確的用戶名和密碼訪問API(c#-HttpClient) - 未經授權的請求
using ApiData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace GetDataFromApi
{
class Program
{
static void Main(string[] args)
{
string uri1 = "https://api.intrinio.com/companies?ticker=AAPL";
ConnectToApi newapi = new ConnectToApi("username", "password", uri1);
Console.ReadLine();
}
public class ConnectToApi
{
public string Username { get; set; }
public string Password { get; set; }
public string Request_url { get; set; }
public ConnectToApi(string username, string password, string url)
{
this.Username = username;
this.Password = password;
this.Request_url = url;
GetAPIToken(Username, Password, Request_url);
}
private static async void GetAPIToken(string userName, string password, string apiBaseUri)
{
try
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userName}:{password}")));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//send request
var responseMessage = await client.GetStringAsync(apiBaseUri);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
}
,如果你對我的代碼,我將非常樂意傾聽任何意見。
謝謝。
lidor
它爲我工作 - 這意味着你應該立即改變你的密碼。 – Crowcoder