user1206480
user1206480

Reputation: 1858

Getting Instagram token with HttpClient

I am trying to make a post request with HttpClient, but it appears that my parameters are not being transmitted as i am getting back a bad request response stating a client_id is needed. Can someone point out to me what I am doing wrong. Here is the concerning code:

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);

Upvotes: 0

Views: 2471

Answers (1)

user1206480
user1206480

Reputation: 1858

Ok, after much experimentation trying to post json to instagram, I have come to the conclusion that Instagram doesn't accept json, not at this endpoint anyways. Somebody correct me if I am wrong. Anyways, here is my solution:

// 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);

This worked flawlessly for me.

Upvotes: 3

Related Questions