Instagram integration in an Android app.

Guides | Tutorial | Uncategorized By 5 years ago

Instagram Integration in Android

Part – 1

Instagram is a new but successful player in social domain nowadays. I am pretty sure many Android developers out there would love to integrate this cool social platform into their apps.

Instagram integration process is quite similar as Twitter integration. But for twitter we have tons of third party libraries, which we don’t have in case of Instagram.

In this blog we’ll see how to get authentication done in your app by using Instagram credentials.

Step 1. Register a new client on Instagram.

1. Open Instagram Developer Website

2. Click on “Register Your Application“

3. Click on “Register a New Client”

4. Enter required details

5. Click Register.

As soon as you’ll press enter and if you have entered all the required details correctly, you’ll see something like this.

Copy and save all these details. We need these things later in our code.

 

Step 2. Authenticate.

 

If your app gets authenticated without any trouble then you’ll get an Access Token that is required to make further request to the Instagram. There are two ways you can get an Access Token from Instagram.

– Server Side Flow (Explicit)

– Client Side Flow (Implicit)

 

In this tutorial we would be talking about server side flow only because when we authenticate our app using implicit method we would only be end up getting Access Token and to get user information we need to make a new request to Instagram but if we follow explicit flow we’ll receive whole lots of information related to the user as well like username, id etc. Enough talk lets code….

1. Save your client id and client secret in your strings.xml so we can access it in our code. You can make a constant class as well to store it inside your app. It is totally up to you where you want to save it. In my case I saved it in my strings.xml.

2. Important URLs,

private static final String AUTHURL = "https://api.instagram.com/oauth/authorize/";
private static final String TOKENURL = "https://api.instagram.com/oauth/access_token";
public static final String APIURL = "https://api.instagram.com/v1";
public static String CALLBACKURL = "Your Redirect URI";

First URL we would be using for authentication, second one is for getting the token and user details and finally third one is API version which we are going to hit whenever we request for some information from Instagram. Last URL is what you registered as a Redirect URI while registering a new client in Step 1.3. MAKE SURE YOUR CALLBACK URL IS EXACTLY THE SAME AS YOU REGISTERED OTHERWISE THE INSTAGRAM WOULD SEND YOU AN ERROR RESPONSE.

3. Form meaningful URLs using above URLs

authURLString = AUTHURL + "?client_id=" + client_id + "&redirect_uri=" + CALLBACKURL + "&response_type=code&display=touch&scope=likes+comments+relationships";
tokenURLString = TOKENURL + "?client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + CALLBACKURL + "&grant_type=authorization_code";

Four things to notice in authURLString – client id, callback url, response_type and scope. First two i hope you are now familiar with, lets talk about other two.

“response_type=code” means that you want a request token after successful authentication not an access token. As i already said we are following the explicit flow. If we were following implicit than it should be “response_type=token”.

“scope” specifies the scope of access or permission for user data. Basically there are four scopes, you can check these scopes in Instagram API documentation.

4. Display the authURLString in a WebView or a Browser for user to authenticate

I strongly advise you not to use browser as it is not a good practice. But still it would be your decision that what is best for your app. In this tutorial we’ll be using WebView.

WebView webView = new WebView(getContext());
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.setWebViewClient(new AuthWebViewClient()); 
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(authURLString);

Take a look at the lines i pointed out in the code. The first line i pointed out is going to deal with the response that we’ll see in minute how and the last line is loading the “authURLString” in our WebView.

5. Deal with the Response

Make a class that extends WebViewClient class to handle the response sent back by the Instagram

public class AuthWebViewClient extends WebViewClient

6. Override the function called shouldOverrideUrlLoading of WebViewClient class

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.startsWith(CALLBACKURL)) {
            System.out.println(url);
	    String parts[] = url.split("=");
            request_token = parts[1];  //This is your request token.
	    InstagramLoginDialog.this.dismiss();
	    return true;
        }
    return false;
}

If you have done everything right so far then you have a request token that we are going to use to get the access token from Instagram.

7. Make a class that extends AsyncTask and put this code in your doInBackground() method

try
{
	URL url = new URL(tokenURLString);
	HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
	httpsURLConnection.setRequestMethod("POST");
	httpsURLConnection.setDoInput(true);
        httpsURLConnection.setDoOutput(true);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpsURLConnection.getOutputStream());
        outputStreamWriter.write("client_id="+client_id+
                                         "&client_secret="+ client_secret +
                                         "&grant_type=authorization_code" +
                                         "&redirect_uri="+CALLBACKURL+
                                         "&code=" + token);

        outputStreamWriter.flush();
        String response = streamToString(httpsURLConnection.getInputStream());
        JSONObject jsonObject = (JSONObject) new JSONTokener(response).nextValue();
        accessTokenString = jsonObject.getString("access_token"); //Here is your ACCESS TOKEN
        id = jsonObject.getJSONObject("user").getString("id");
        username = jsonObject.getJSONObject("user").getString("username"); //This is how you can get the user info. You can explore the JSON sent by Instagram as well to know what info you got in a response

}
catch (Exception e)
{
      e.printStackTrace();
}

In this piece of code we are opening an HTTPS connection and filling it with stuff which is required by Instagram to generate an access token for us. Make sure you save this access token somewhere safer. I saved it in my SharedPreference so i can use it whenever i want to make a request to the Instagram server that requires an authentication.

In next tutorial i would explain how can we get all the user photos from Instagram.

Thanks for reading.

Download Sample Source Code – http://ftp.b2cloud.com.au//InstaDemo.zip

  • this line httpsURLConnection.getInputStream() throws file not found exception, after i checked the response code of httpsURLConnection I found it 400

  • Great tutorial, but is there a sample project with these code? I’m getting a bit confused :-/

    • varun_b2cloud

      I am so sorry that you had to wait for so long, i have posted a link to source code. Cheers!!

  • Hi,

    Thanks for your blog.
    Can you please share a sample application demo with me.

  • Nice tutorial!

    There seem to be, however, some bugs with the code. I was able to fixe the getInputStream() error (see @Antoung’s reply) by changing:

    1) Set tokenURLString to be simply TokenURL, without the parameters, which will go into the POST message.

    2) Change

    “client_id=”+client_id+
    “client_secret=”+ client_secret +
    “grant_type=authorization_code” +
    “redirect_uri=”+CALLBACKURL+
    “code=” + token
    to: (note the added “&”)

    “client_id=”+client_id+
    “&client_secret=”+ client_secret +
    “&grant_type=authorization_code” +
    “&redirect_uri=”+CALLBACKURL+
    “&code=” + token

    • varun_b2cloud

      Thanks KuangX for highlighting and fixing the error. I have fixed it in code as well. Cheers!!

  • Mihir

    Getting a FileNotFoundException. How to resolve this ?

    • varun_b2cloud

      That’s weird!! By the way i have posted a source code, that might help you i guess.

  • Mihir

    Getting a FileNotFoundException. How to resolve this ?

  • parag chauhan

    Thanks for sharing nice tutorial.

    Can you upload source code for this tutorial?

  • varun_b2cloud

    Hey Guys, Sorry for not responding for so long. I would upload a working sample really soon. Cheers!!

  • parag chauhan

    Thanks varun …wait for your working code.. 🙂 🙂

    • varun_b2cloud

      Sorry for delay. I have posted a link, take a look. Cheers!!

      • Rakesh

        your damn link is not working please provide correct link or remove that link

  • Hi, I cannot dismiss the InstaLoginDialog with dismiss() in 4.0 and over, do you have any idea?

    setCancelable(true) does not help.

    Thank you in advance.

    • my solution is using hide() instead of dismiss(), although hide() is just hidden, of course :D. If you have better solution, please let know.

    • my solution is using hide() instead of dismiss(), although hide() is just hidden, of course :D. If you have better solution, please let know.

  • Set InstaLoginDialog.this.dismissDialog(); instead of InstaLoginDialog.this.hide();

    • varun_b2cloud

      Thanks for suggestions. Cheers 🙂

  • Chetan

    Hi varun thanks for such a wonder full tutorial for instagram integration. I am done with basic steps and getting response. But still i don’t get it How to upload image from application to instagram .
    please help me on this.
    Thanks,
    chetan.

    • varun_b2cloud

      Hi Chetan, when last time i checked, instagram APIs didn’t have the support for uploading images. That can only be done when you use Instagram’s official app.

  • Chetan

    Hi varun thanks for such a wonder full tutorial for instagram integration. I am done with basic steps and getting response. But still i don’t get it How to upload image from application to instagram .
    please help me on this.
    Thanks,
    chetan.

  • Christoph Portmann

    I am a bit confused, since the Instagram Api guide says “You should never ship your client secret onto devices you don’t control.” But following this tutorial I ship the client secret to user’s device. Can you explain me if this is the case, and if yes why it is legitim?

    • varun_b2cloud

      Do what Instagram recommends. This is just a tutorial of how to make things work with Instagram APIs but at the end of the day you should always follow what official APIs developers recommend you.

  • Vignesh

    the sample source code link does’nt work, pls update the link.

  • Rakesh

    no interconnection between the codes didnt told how many java files to create ?
    no sample code? really hard to follow 🙁

    • varun_b2cloud

      I am updating the link to the source code shortly. I just realised that old link is dead for some reason. Sorry for the inconvenience 🙁

  • Autumn

    When I Register new Client, how to set the Redirect URI and the “Website” and “Oauth rediret_uri”?

    • varun_b2cloud

      I am updating the Link to the source code shortly. I just realised it that old link is dead for some reason. Sorry for the inconvenience 🙁

  • ensr

    link doesn’t working.

  • james

    i am register of my app in Instagram and login with register account its works fine but login with other user account its not work ..how to solve this please help me

  • abbas nikzad

    pls help ! when we dont have access_token before and we want get it after user login , then how we can access it from url fragment to save in application . what about defining redirect_uri for android apps ?