通过FatSecret Api 2.0 c#获取响应

时间:2019-06-12 09:12:13

标签: c# api httpclient

我设法通过以下指南获取令牌:https://platform.fatsecret.com/api/Default.aspx?screen=rapiauth2,但是我无法正确获得响应。代码在哪里出错了?

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private async void BtnFoodApi_Click(object sender, RoutedEventArgs e)
    {
        // --- Get Token --

        HttpClient client = new HttpClient();
        var byteArray = Encoding.ASCII.GetBytes("9276456b47524b479cbdaf7cf5792bbf:0366d2fc646e4b6f89bf11bddbaec6a4");
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        var values = new Dictionary<string, string>
        {
           { "scope", "basic" },
           { "grant_type", "client_credentials" }
        };
        var content = new FormUrlEncodedContent(values);
        var response = await client.PostAsync("https://oauth.fatsecret.com/connect/token", content);

        var responseString = await response.Content.ReadAsStringAsync();

        var serializer = new DataContractJsonSerializer(typeof(RootObject));

        var ms = new MemoryStream(Encoding.UTF8.GetBytes(responseString));
        var data = (RootObject)serializer.ReadObject(ms);


        // --- Get responce --

        var http = new HttpClient();

        http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", data.access_token);

        var valuesRequest = new Dictionary<string, string>
        {
           { "application", "json" },
        };

        var contentRequest = new FormUrlEncodedContent(valuesRequest);

        var responseRequest = await http.PostAsync("https://platform.fatsecret.com/rest/server.api", contentRequest);

        //Parameters: method=foods.search&search_expression=toast&format=json // How can I call Api 2.0 with these parameters?

        //var responseRequestString = await responseRequest.Content.ReadAsStringAsync();
    }
}

[DataContract]
public class RootObject
{
    [DataMember]
    public string access_token { get; set; }

    [DataMember]
    public int expires_in { get; set; }

    [DataMember]
    public string token_type { get; set; }
}

我想进入Json字符串中的responseRequest字符串字符串。

this page的底部,有关于此步骤的指南,我试图用c#编写它,但不正确。

谢谢!

1 个答案:

答案 0 :(得分:0)

您不需要对Bearer令牌进行base64编码-仅用于混淆基本身份验证。您可以按原样使用字符串。

http.DefaultRequestHeaders.Authorization =
        new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", data.access_token);