简体   繁体   中英

Getting "Bad Request" when using RestSharp

I am living in Denmark where we have the ability to pull all data regarding our power usage from the website Eloverblik.dk .

They have even provided a nice API, so you can make your own programs that pulls the data from their website:

https://api.eloverblik.dk/CustomerApi/index.html

However:

Assume you have the following C# prof of concept code:

using RestSharp;
using RestSharp.Authenticators;

var token = "eyJ...";
var client = new RestClient("https://api.eloverblik.dk") 
{
    Authenticator = new JwtAuthenticator(token)
};

/* Get power usage from June 1st 2022 until September 1st 2022 */
var request = new RestRequest("api/meterdata/getmeterreadings/2022-06-01/2022-09-01");
var response = await client.GetAsync(request);

Console.WriteLine(response.Content);

When I run the code I get an error code "BadRequest" when I try to call await client.GetAsync .

What am I doing wrong?

They write in the API that the token is formattet as Bearer {token} , but I thought that JwtAuthenticator did that for me?

It seems that you call API incorrectly.

Check again documentation on API at https://api.eloverblik.dk/CustomerApi/index.html .

  1. getMeterReadings is a POST method, not a GET (so, you need to call client.PostAsync and not client.GetAsync )
  2. getMeterReadings expects also JSON-body to be sent (with list of metering points).

Also, I would recommend you to test your requests using some HTTP-request tool (ie Postman) and when you're pretty sure that request works move it into C#.

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