タス デザイン グループ

Read Article

OAuth対応のオープンAPIを使う(端末連携・サーバ連携)

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fxos.androidtips37"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar" >
        <activity
            android:name="com.example.fxos.androidtips37.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="CallBackActivity"
            android:label="@string/app_name"
            android:launchMode="singleInstance" >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/callback_scheme" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_start_oauth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="@string/btn_start_oauth" />

</LinearLayout>

MainActivity.java

package com.example.fxos.androidtips37;

import twitter4j.TwitterException;
import twitter4j.auth.OAuthAuthorization;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationContext;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

    public static RequestToken mRequestToken = null;

    public static OAuthAuthorization mOAuthAuthorization = null;

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

    public void onClick(View view) {
        // start OAuth authorization
        if (view.getId() == R.id.btn_start_oauth) {
            AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    // read twitter4J settings
                    Configuration conf = ConfigurationContext.getInstance();

                    // create OAuth Object
                    mOAuthAuthorization = new OAuthAuthorization(conf);

                    // set consumer key and secret key
                    mOAuthAuthorization.setOAuthConsumer(Util.CONSUMER_KEY, Util.SECRET_KEY);
                    try {
                        // make request token object
                        mRequestToken = mOAuthAuthorization.getOAuthRequestToken(Util
                                .getCallbackUrl(MainActivity.this));
                    } catch (TwitterException e) {
                        e.printStackTrace();
                    }

                    return null;
                }

                protected void onPostExecute(Void result) {
                    if (mRequestToken != null) {
                        // move to permission page
                        String url;
                        url = mRequestToken.getAuthorizationURL();
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    }
                }

            };
            task.execute();
        }
    }
}

CallBackActivity.java

package com.example.fxos.androidtips37;

import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

import android.app.ListActivity;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class CallBackActivity extends ListActivity {
    private AccessToken token = null;

    private ResponseList<Status> mTimeLine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                // get uri from twitter Authentication screen of Twitter
                Uri uri = getIntent().getData();

                if (uri != null
                        && uri.toString().startsWith(Util.getCallbackUrl(CallBackActivity.this))) {
                    // get oauth_verifier
                    String verifier = uri.getQueryParameter(Util.VERIFIER);
                    try {
                        // get AccessToken Object
                        token = MainActivity.mOAuthAuthorization.getOAuthAccessToken(
                                MainActivity.mRequestToken, verifier);

                        Twitter tw = new TwitterFactory().getInstance();
                        tw.setOAuthConsumer(Util.CONSUMER_KEY, Util.SECRET_KEY);
                        tw.setOAuthAccessToken(token);

                        // get self TimeLine
                        mTimeLine = tw.getUserTimeline(tw.getAccountSettings().getScreenName());
                    } catch (TwitterException e) {
                        e.printStackTrace();
                    }
                }

                return null;
            }

            protected void onPostExecute(Void result) {
                // show TimeLine list
                TimeLineAdapter adapter = new TimeLineAdapter(CallBackActivity.this,
                        android.R.layout.simple_list_item_2, mTimeLine);
                getListView().setAdapter(adapter);
            }

        };
        task.execute();
    }

    class TimeLineAdapter extends ArrayAdapter<Status> {
        private int textViewResourceId;

        public TimeLineAdapter(Context context, int textViewResourceId,
                ResponseList<Status> statusArray) {
            super(context, textViewResourceId, statusArray);
            this.textViewResourceId = textViewResourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = inflater.inflate(textViewResourceId, null);
            }
            Status status = getItem(position);

            // set tweet
            TextView text1 = (TextView)v.findViewById(android.R.id.text1);
            text1.setText(status.getText());

            // set user name
            TextView text2 = (TextView)v.findViewById(android.R.id.text2);
            text2.setText(status.getUser().getName());

            return v;
        }

    }
}

Util.java

package com.example.fxos.androidtips37;

import android.content.Context;
import android.net.Uri;

public class Util {
    // This is sample value. Please change the values ​​to suit your
    // application.
    public static final String CONSUMER_KEY = "pJZKHkmWjbBGbxp2m6EqtiM9n";

    // This is sample value. Please change the values ​​to suit your
    // application.
    public static final String SECRET_KEY = "fL4Jxijza0Ldb2fWCbYTmBrZUyiA2vM1arZTd8LWwbwnfun7Xo";

    public static final String VERIFIER = "oauth_verifier";

    // make callback url
    public static String getCallbackUrl(Context context) {
        Uri.Builder builder = new Uri.Builder();
        builder.scheme(context.getString(R.string.callback_scheme)).authority(
                CallBackActivity.class.getSimpleName());

        return builder.toString();
    }

}

manifest.webapp

{
  "name": "oauth",
  "description": "37_oauth",
  "launch_path": "/index.html",
  "type": "privileged",
  "icons": {
    "64": "/img/icon/app-icon64.png",
    "128": "/img/icon/app-icon128.png"
  },
  "developer": {
    "name": "TAS Design Group",
    "url": "http://tasdg.co.jp/"
  },
  "permissions": {
    "systemXHR": {}
  },
  "redirects": [
    {"from": "http://tasdg.co.jp/",
      "to": "/index.html"}
  ],
  "default_locale": "ja"
}

CSS (style/style.css)

@charset "UTF-8";

html {
  height: 100%;
  font-size: 62.5%;
}

body {
  margin: 0;
  height: 100%;
  display: block;
  overflow: hidden;
  font-family: sans-serif;
  background-color: #ffffff;
}

JS (js/thirdparty)

index.html

<!DOCTYPE html>
<html lang="ja" dir="ltr">
<head>
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
  <meta charset="utf-8">
   <title>OAuth authentication</title>
   <link rel="stylesheet" href="style/style.css">

   <script type="text/javascript" src="js/thirdparty/oauth.js"></script>
   <script type="text/javascript" src="js/thirdparty/sha1.js"></script>
   <script type="text/javascript" src="js/main.js"></script>

</head>
<body>
  <section>
    <header>
      <h1>OAuth authentication</h1>
    </header>
    <article>View a timeline of Twitter using OAuth authentication</article>
    <button id="btn">Authorize by Twitter</button>
    <div id="msg"></div>
  </section>
</body>
</html>

main.js

var twitter = {
  consumerKey: 'pJZKHkmWjbBGbxp2m6EqtiM9n',
  consumerSecret: 'fL4Jxijza0Ldb2fWCbYTmBrZUyiA2vM1arZTd8LWwbwnfun7Xo',


  errorfunc: function() {
    console.log('error');
  },

  //---------------------
  getRequestToken: function(callback) {
    var accessor = {
      consumerSecret: this.consumerSecret,
      tokenSecret: ''
    };

    var message = {
      method: 'GET',
      action: 'https://api.twitter.com/oauth/request_token',
      parameters: {
        oauth_version: '1.0',
        oauth_signature_method: 'HMAC-SHA1',
        oauth_consumer_key: this.consumerKey,
      }
    };

    OAuth.setTimestampAndNonce(message);
    OAuth.SignatureMethod.sign(message, accessor);
    var target = OAuth.addToURL(message.action, message.parameters);

    this.getserverdata(target, function(data) {
      var ret = splitdata(data);
      callback(ret);
    });
  },

  //---------------------
  getAccessToken: function(callback) {
    var accessor = {
      consumerSecret: this.consumerSecret,
      tokenSecret: localStorage.getItem('request_token_secret')
    };

    var message = {
      method: 'GET',
      action: 'https://api.twitter.com/oauth/access_token',
      parameters: {
        oauth_version: '1.0',
        oauth_signature_method: 'HMAC-SHA1',
        oauth_consumer_key: this.consumerKey,
        oauth_token: localStorage.getItem('request_token'),
        oauth_verifier: localStorage.getItem('oauth_verifier')
      }
    };

    OAuth.setTimestampAndNonce(message);
    OAuth.SignatureMethod.sign(message, accessor);
    var target = OAuth.addToURL(message.action, message.parameters);

    this.getserverdata(target, function(data) {
      var ret = splitdata(data);
      callback(ret);
    });
  },

  //---------------------
  getTimeLine: function(callback) {
    var accessor = {
      consumerSecret: this.consumerSecret,
      tokenSecret: localStorage.getItem('access_token_secret')
    };

    var message = {
      method: 'GET',
      action: 'https://api.twitter.com/1.1/statuses/home_timeline.json',
      parameters: {
        oauth_version: '1.0',
        oauth_signature_method: 'HMAC-SHA1',
        oauth_consumer_key: this.consumerKey,
        oauth_token: localStorage.getItem('access_token'),
        count: '50'
      }
    };

    OAuth.setTimestampAndNonce(message);
    OAuth.SignatureMethod.sign(message, accessor);
    var target = OAuth.addToURL(message.action, message.parameters);

    this.getserverdata(target, function(data) {
      callback(data);
    });
  },

  //---------------------
  getserverdata: function(target, callback) {
    var xhr = new XMLHttpRequest({
      mozSystem: true
    });
    xhr.open('GET', target, true);

    xhr.onreadystatechange = function() {
      if ((xhr.readyState === 4 && xhr.status === 200) || (xhr.readyState === 4 && xhr.status === 0)) {
        callback(xhr.responseText);
      } else if (xhr.statusText !== 'OK') {
        errorfunc();
      }
    };
    xhr.onerror = function() {
      errorfunc();
    };
    xhr.send(null);
  }
};

function splitdata(data) {
  var a = [];
  var dat = data.split('&');
  for (var i = 0; i < dat.length; i++) {
    var d = dat[i].split('=');
    a[d[0]] = d[1];
    a.length++;
  }
  return a;
}

function update(data) {
  var dat;
  for (var i = 0; i < data.length; i++) {
    if (typeof(dat) === 'undefined') dat = '<p>' + data[i].user.name + ' : ' + data[i].text + '</p>';
    else dat += '<p>' + data[i].user.name + ' : ' + data[i].text + '</p>';
  }
  document.getElementById('msg').innerHTML = dat;
}

window.addEventListener('load', function() {

  var param = window.location.search.substring(1, window.location.search.length);
  var dat = splitdata(param);

  if (dat.length !== 0) {
    disptimeline();
  }

  document.getElementById('btn').onclick = function() {

    twitter.getRequestToken(function(res) {
      localStorage.setItem('request_token', res['oauth_token']);
      localStorage.setItem('request_token_secret', res['oauth_token_secret']);
      window.location.href = 'https://api.twitter.com/oauth/authorize?oauth_token=' + res['oauth_token'];
    });
  };

  function disptimeline() {

    localStorage.setItem('oauth_verifier', dat['oauth_verifier']);
    twitter.getAccessToken(function(res) {
      localStorage.setItem('access_token', res['oauth_token']);
      localStorage.setItem('access_token_secret', res['oauth_token_secret']);
      twitter.getTimeLine(function(data) {

        var timeline = JSON.parse(data);
        update(timeline);
      });
    });
  }

});
Return Top