Sample code for 30+ languages & platforms
Android™

Configure OAuth 1.0a Authentication for REST

See more REST Examples

Demonstrates Rest.SetAuthOAuth1, which associates an OAuth1 provider so Chilkat computes the OAuth 1.0/1.0a signature for each request. The second argument selects whether OAuth parameters are placed in the query string or the Authorization header.

Background. OAuth 1.0a signs each request using the consumer key/secret and the access token/secret. Chilkat generates the nonce, timestamp, and signature automatically for every request sent through the object.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    CkRest rest = new CkRest();
    boolean bTls = true;
    boolean bAutoReconnect = true;
    success = rest.Connect("example.com",443,bTls,bAutoReconnect);
    if (success == false) {
        Log.i(TAG, rest.lastErrorText());
        return;
        }

    //  Configure OAuth 1.0a request signing.  Provide the consumer credentials and the access token
    //  credentials; Chilkat computes the OAuth signature for each request.
    CkOAuth1 oauth1 = new CkOAuth1();
    //  Normally you would not hard-code secrets in source.  You should instead obtain them from an
    //  interactive prompt, environment variable, or a secrets vault.
    oauth1.put_ConsumerKey("CONSUMER_KEY");
    oauth1.put_ConsumerSecret("CONSUMER_SECRET");
    oauth1.put_Token("ACCESS_TOKEN");
    oauth1.put_TokenSecret("ACCESS_TOKEN_SECRET");
    oauth1.put_SignatureMethod("HMAC-SHA1");

    //  The 2nd argument selects whether OAuth parameters are placed in the query string (true) or the
    //  Authorization header (false).
    boolean bUseQueryParams = false;
    success = rest.SetAuthOAuth1(oauth1,bUseQueryParams);
    if (success == false) {
        Log.i(TAG, rest.lastErrorText());
        return;
        }

    String responseText = rest.fullRequestNoBody("GET","/api/resource");
    if (rest.get_LastMethodSuccess() == false) {
        Log.i(TAG, rest.lastErrorText());
        return;
        }

    Log.i(TAG, responseText);

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}