How to get OAth Token with HttpClient?

2019-08-28 09:45发布

I need to get a token for a REST call. The token should be in a JSON result.

https://github.com/bic-boxtech/BIC-BoxTech-API-Samples/wiki/Authentication

Here is the way I tried it:

private async void GetBicDataAsync()
    {
        HttpClient _bicAothClient;

        _bicAothClient = new HttpClient();
        _bicAothClient.DefaultRequestHeaders.Add("Authorization", "Basic YmljYXBwOmJpY3NlY3JldGFwcA==");

        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", Constants.BicAothUser),
            new KeyValuePair<string, string>("password", Constants.BicAothPassword)
        });

        var result = await _bicAothClient.PostAsync(Constants.BicAothEndpoint, content);
    }

But I get an 400:

{"statusCode":400,"status":400,"code":400,"message":"Invalid request: method must be POST","name":"invalid_request"}

What did I wrong. I thing it's a small stupid fail. Can someone help me please.

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-28 10:35

if you get the content as a string you can use this code to get every values from the endpoint separated:

        //  Ask if the container is found in dataBase
        if (bicData.ReasonPhrase == "OK")
        {
            //  Get content as string
            var containerDataString = await bicData.Content.ReadAsStringAsync();

            //  Get a list of JObjects out of the content string
            IEnumerable<JObject> objs = JsonConvert.DeserializeObject<List<JObject>>(containerDataString);

            //  Select the first JObject of the list
            JObject containerDataJObject = objs.FirstOrDefault();

            //  Assign values as string
            var tareKg  = containerDataJObject["tare_kg"].Value<string>();
            var tareLb  = containerDataJObject["tare_lbs"].Value<string>();
            var netKg   = containerDataJObject["max_payload_kg"].Value<string>();
            var netLb   = containerDataJObject["max_payload_lbs"].Value<string>();
            var maxKg   = containerDataJObject["max_gross_mass_kg"].Value<string>();
            var maxLb   = containerDataJObject["max_gross_mass_lbs"].Value<string>();
            var cubicM  = containerDataJObject["cubic_capacity_cbm"].Value<string>();
            var cubicFt = containerDataJObject["cubic_capacity_cuft"].Value<string>();

           // And so on...
        }

You get the full list of objects in the Swagger example.

查看更多
相关推荐>>
3楼-- · 2019-08-28 10:44

I contacted the provider and see... the wiki was wrong. Both URLs I needed were incorrect. Now here is a code to get everything you want:

private async void GetBicDataAsync()
        {
            //  HttpClient to get the token
            HttpClient bicAothClient;
            bicAothClient = new HttpClient();

            //  Add header
            bicAothClient.DefaultRequestHeaders.Add("Authorization", "Basic YmljYXBwOmJpY3NlY3JldGFwcA==");

            //  Set parameters
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", <USERNAME>),
                new KeyValuePair<string, string>("password", <PASSWORD>)
            });

            //  POST async
            var result = await _bicAothClient.PostAsync("https://app.bic-boxtech.org/oauth/token/", content);

            //  Get content as string
            var contentString = await result.Content.ReadAsStringAsync();

            //  Parse content, to get the accessToken
            var r = JToken.Parse(contentString);
            var token = r["accessToken"].Value<string>();


            //  HttpClient to get container data
            HttpClient _bicDataClient;
            bicDataClient = new HttpClient();

            //  Add accessToken to header
            bicDataClient.DefaultRequestHeaders.Add("Authorization", ("Bearer " + token));

            //  Get container data
            var bicData = await bicDataClient.GetAsync("https://app.bic-boxtech.org/api/v2.0/container/" + <CONTAINERNUMBER>);

            //  Get content as string
            var containerDataString = await bicData.Content.ReadAsStringAsync();

            //  Do what you need with this content
        }
查看更多
登录 后发表回答