繁体   English   中英

在C#中使用标头,用户名和密码调用Api

[英]Calling Api with header, username and password in C#

我正在尝试从此api codaBox获取数据,我用招摇 过头测试了它,但是当我尝试使用我得到的错误代码是401。我使用的是正确的标题,用户名和密码。

我用相同的凭据大张旗鼓地测试了它,并获得了数据。

try
{
    var byteArray = Encoding.ASCII.GetBytes("Username:password");
    Client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
    Client.BaseAddress = new Uri("https://myurl");

    Client.DefaultRequestHeaders.Add("X-Software-Company", "myToken");
    HttpResponseMessage response = await Client.GetAsync("");
    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();
    // Above three lines can be replaced with new helper method below
    // string responseBody = await client.GetStringAsync(uri);

    Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
    Console.WriteLine("\nException Caught!");
    Console.WriteLine("Message :{0} ", e.Message);
}

我想获取200个状态代码。

您需要将"Username:password"替换为实际用户名和密码,并用以下分隔符: "{your actual username}:{your actual password}"

Web也是UTF8(Ascii有时因为它是子集而起作用),但并不总是这样:

var byteArray = Encoding.UTF8.GetBytes("Username:password");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM