使用身份验证凭据的简单C#API Get请求?

2024-09-29 22:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我是C#编程的初学者。我有使用Python的经验,这正是我试图用C#复制的东西

import requests, json

api_user = "userexample@example.com"
api_key = "keyexample"
url = "https://api.example.com/"

response = requests.get(url, auth=(api_user, api_key))
json_response = response.json()

print(json_response)

那代码是什么样子的?谢谢


Tags: keyimportcomapijsonurlexampleresponse
1条回答
网友
1楼 · 发布于 2024-09-29 22:25:45

您可以使用HttpClient库来连接api服务器。 下面是api基本身份验证的示例代码。 最后一定要调用Dispose(),否则您可能会遇到一些GC问题

public static class Program
    {
        public static async Task Main(string[] args)
        {
            var apiUser = "userexample@example.com";
            var apiKey = "keyexample";
            var url = "https://api.example.com/";

            var client = new HttpClient();
            client.BaseAddress = new Uri("https://api.example.com/");

            var authToken = Encoding.ASCII.GetBytes($"{apiUser}:{apiKey}");
            client.DefaultRequestHeaders.Authorization = 
                new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
            var response = await client.GetAsync(url);
            var content = response.Content;
            client.Dispose();
        }
    }

相关问题 更多 >

    热门问题