请求access_token Instagram

时间:2014-08-02 11:40:18

标签: c# asp.net-mvc api instagram

我遇到了以下问题:

我正在尝试将Instagram应用到我的网站中。但是我仍然坚持我需要获取Acces令牌的步骤。 api的文档说我需要这样请求:

curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \https://api.instagram.com/oauth/access_token

我使用ASP.NET,因此我发现了这个等效的OAuth 2.0 In .NET With Instagram API

NameValueCollection parameters = new NameValueCollection();
            parameters.Add("client_id", "ssdfsdfsdfsdfsdf");
            parameters.Add("client_secret", "sdsdfdsfsdfsdfsdfsdfsdf");
            parameters.Add("grant_type", "authorization_code");
            parameters.Add("redirect_uri", "http://localhost:2422/LoginsGuests/GetLoginPage");
            parameters.Add("code", code);

            WebClient client = new WebClient();
            var result = client.UploadValues("https://api.instagram.com/oauth/access_token", parameters);

            var response = System.Text.Encoding.Default.GetString(result);

但是我一直得到:     System.Net.WebException:远程服务器返回错误:(400)Bad Request。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

几乎在那里,instagram api期望POST不是GET。

添加" POST"参数。

var result = client.UploadValues(" https://api.instagram.com/oauth/access_token"," POST",参数);

同时检查Instagram设置 - >重定向网址。

然后这可能有助于不要忘记添加对Newtonsoft.Json的引用。在.Net版本4.5.1:

using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

namespace Instagram
{
    public class InstagramClient
    {
        public InstagramClient(string code)
        {
            GetToken(code);
        }

        private void GetToken(string code)
        {
            using (var wb = new WebClient())
            {
                var parameters = new NameValueCollection
                                 {
                                     {"client_id", "ClientId"},
                                     {"client_secret", "ClientSecret"},
                                     {"grant_type", "authorization_code"},
                                     {"redirect_uri", "RedirectUri"},
                                     {"code", code}
                                 };

                var response = wb.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
                string json = Encoding.ASCII.GetString(response);

                try
                {
                    var OauthResponse = (InstagramOAuthResponse)    Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(InstagramOAuthResponse));
                }
                catch (Exception ex)
                {
                    //handle ex if needed.
                }
            }
        }

        public class InstagramOAuthResponse
        {
            public string access_token { get; set; }
            public User user { get; set; }
        }

        public class User : System.Security.Principal.IIdentity
        {
            public string username { get; set; }
            public string website { get; set; }
            public string profile_picture { get; set; }
            public string full_name { get; set; }
            public string bio { get; set; }
            public string id { get; set; }

            public string OAuthToken { get; set; }

            public string AuthenticationType
            {
                get { return "Instagram"; }
            }

            public bool IsAuthenticated
            {
                get { return !string.IsNullOrEmpty(id); }
            }

            public string Name
            {
                get
                {
                    return String.IsNullOrEmpty(full_name) ? "unknown" : full_name;
                }
            }
        }
    }
}

答案 1 :(得分:0)

如果您更喜欢HttpWebRequest类:

var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/access_token/");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

var requestDetails = "client_id=" + AppConfig.InstagramClientId;
requestDetails += "&client_secret=" + AppConfig.InstagramClientSecret;
requestDetails += "&grant_type=authorization_code";
requestDetails += "&redirect_uri=" + redirectUrl;
requestDetails += "&code=" + exchangeCode;

byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
request.ContentLength = bytes.Length;

using (Stream outputStream = request.GetRequestStream())
{
    outputStream.Write(bytes, 0, bytes.Length);
}

var response = request.GetResponse();
var code = ((HttpWebResponse)response).StatusCode;

if (code == HttpStatusCode.OK)
{
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
        var jsonString = streamReader.ReadToEnd();
        var accessToken = ParseAccessToken(jsonString);
        return accessToken;
    }
}