简体   繁体   中英

Cannot access API with correct username and password(c#-HttpClient)-Unauthorized Request

i am trying an api and receive data. i got the api username and password but when im trying to connect i get an unauthorized request. i thing something is wrong with my request-header -authentication. here is my code:

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);

                }
            }
        }
    }

}

if you have any comments on my code i would love to hear it.

thanks.

lidor

This might Help

you need to get RestSharp for this to work

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);

and you can try to convert it to an object by

 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;
        }

and i do recommend of using http://json2csharp.com/ to create your C# Object
More Information

To get the Value that is used for authorization you can use this method

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

to get the exact value make sure the username and password are concatenated, (username first , password second) and then passed to the method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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