2

Im trying to work on an android application which simply retrieves pictures from the api. Im trying to use retrofit but im consufed how to use it. also I dont understand how to get the access tokens? Do i need the user to login? Cant I simply get images from instagram not particularly related to any user?

I tried something like

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mButton = (Button) findViewById(R.id.button);

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse("https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code"); // missing 'http://' will cause crashed
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    });

this leads me to a login page and then it promts me to put in user details and after that gives me some sort of authentication error.

I cannot seem to understand the insta documentation

Hasan Nagaria
  • 253
  • 6
  • 16

1 Answers1

1

That what I did to do the login:

Just load the web view after the user clicked OK and then extract the code authorization:

webView?.settings?.javaScriptEnabled = true
        webView?.loadUrl(AuthenticationPresenter.urlAuthentication())
        webView?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean {
                if (url.contains("code=")) {
                    presenter.extractAuthorizationCode(url)
                    return true
                }
                return false
            }
        }

fun urlAuthentication() = "https://api.instagram.com/oauth/authorize/" +
                "?client_id=$CLIENT_ID" +
                "&redirect_uri=$REQUEST_URL_CALLBACK" +
                "&scope=${USER_PROFILE},${USER_MEDIA}" +
                "&response_type=$RESPONSE_TYPE"

Getting the code authorization from the URL:

override fun extractAuthorizationCode(url: String) {
        val uri: Uri = Uri.parse(url)
        val code = uri.getQueryParameter("code")
        if (code != null)
            view?.authorizationCodeSuccess(code)
        else
            view?.authorizationCodeFail()
    }

After getting the code authorization, you should be able to get the access token.

Here's an example using Retrofit2:

interface AuthenticationApiHelper {

    @FormUrlEncoded
    @POST("/oauth/access_token")
    suspend fun getCredentials(
        @Field("code") code: String,
        @Field("client_id") client: String = CLIENT_ID,
        @Field("client_secret") secret: String = CLIENT_SECRET,
        @Field("grant_type") type: String = GRANT_TYPE,
        @Field("redirect_uri") uri: String = REQUEST_URL_CALLBACK
    ): Credentials
}
Douglas Mesquita
  • 860
  • 1
  • 13
  • 30