使用HttpClient获取Instagram令牌

时间:2013-06-28 09:09:31

标签: c# asp.net-mvc instagram

我正在尝试使用HttpClient发布一个帖子请求,但看起来我的参数没有被传输,因为我收到一个错误的请求响应,说明需要client_id。有人可以向我指出我做错了什么。以下是相关代码:

var authLinkUri = 
            new Uri(@"https://api.instagram.com/oauth/access_token");

        // define the request parameters
        var requestObj = new Models.RequestAccessToken()
                             {
                                 client_id = config.ClientId,
                                 client_secret = config.ClientSecret,
                                 grant_type = "authorization_code",
                                 redirect_uri = config.RedirectURI,
                                 code = code
                             };

        // serialize the obj for transfer
        var requestObjSer = JsonConvert.SerializeObject(requestObj);

        // create the content obj
        var content = new StringContent(requestObjSer, Encoding.UTF8, "application/json");

        // make request for auth token
        var response = await requestToken.PostAsync(authLinkUri, content);

1 个答案:

答案 0 :(得分:1)

好的,经过多次尝试将json发布到Instagram后,我得出的结论是Instagram不接受json,而不是在此端点。如果我错了,有人会纠正我。无论如何,这是我的解决方案:

// define key,value pair
        var postValues = new List<KeyValuePair<string, string>>
                             {
                                 new KeyValuePair<string, string>
                                     ("client_id",
                                      config.ClientId),
                                 new KeyValuePair<string, string>
                                     ("client_secret",
                                      config.ClientSecret),
                                 new KeyValuePair<string, string>
                                     ("grant_type",
                                      "authorization_code"),
                                 new KeyValuePair<string, string>
                                     ("redirect_uri",
                                      config.RedirectURI),
                                 new KeyValuePair<string, string>("code", code)
                             };

        // now encode the values
        var content = new FormUrlEncodedContent(postValues);

// make request for auth token
        var response = await requestToken.PostAsync(authLinkUri, content);

这对我来说完美无缺。