无法使用正确的用户名和密码(c#-HttpClient)-Unauthorized Request访问API

时间:2017-08-14 11:14:05

标签: c# api httprequest

我正在尝试api并接收数据。我得到了api用户名和密码,但是当我试图连接时,我收到了未经授权的请求。我的request-header -authentication有问题。 这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

这可能会有帮助

你需要让RestSharp才能正常工作

var client = new RestClient("https://api.intrinio.com/companies?ticker=AAPL");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Basic MGU0NWIxZmIwZDFlMGNkMDEzY2Y2Y2I5MmRlNjk2N2M6MjNjYjM3OTQ3ZmFmMjQ0OWI1MWRjMWQ1NGU2ZGE1Zjc=");
IRestResponse response = client.Execute(request);

您可以尝试通过

将其转换为对象
 try
        {
            dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(response.Content, new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore });
            return x;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return null;
        }

我建议使用http://json2csharp.com/ 创建C#对象
更多信息

要获取用于授权的值,您可以使用此方法

 public static string Base64Encode(string key)
 {
    var value = System.Text.Encoding.UTF8.GetBytes(key);
    return System.Convert.ToBase64String(value);
 }

获取确切的值,确保连接用户名和密码,(用户名优先,密码秒),然后传递给方法