Android Imitation Sina microblogging oauth2.0 licensing Interface Implementation code (2) _android

Source: Internet
Author: User
Tags throwable

oauth2.0 licensing interface, approximate flowchart:

Prerequisite Preparation:

Apply for Appkey and appsecret:http://open.weibo.com/on Sina open platform.
Familiar with oauth2.0 agreement, relevant knowledge: http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
OAuth2 Access_token Interface: Http://open.weibo.com/wiki/OAuth2/access_token

Code detailed

The general idea is as follows: Establish a WebView load authorization interface, authorize callback address please refer to Constants.java inside have detailed annotation. The method is recalled when the page is loaded, and if the user agrees (enter his or her microblog account password), it succeeds in acquiring the code and sending an asynchronous POST request Access_token If the Access_token information is successfully obtained, Then use Sharedpreferences to save all the important information and jump to the main interface.
The request parameters for the asynchronous post setting must correspond to the request parameter one by one required in the OAuth2 Access_token interface.
The Access_token obtained here are the prerequisite request parameters for each subsequent interface.

* * Custom Licensing interface, request token/public class Oauthactivity extends activity {//Save data Information private sharedpreferences preferences;
 private static final String TAG = "oauthactivity";
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.webview);
  Acquiring Sharedpreferences objects that can only be read and written by this program preferences = getsharedpreferences ("OAuth2.0", context.mode_private);
  WebView Load Callback page WebView WebView = (webview) Findviewbyid (R.id.webview);
  Management WebView WebSettings websettings = webview.getsettings ();
  Enable JavaScript Invoke feature websettings.setjavascriptenabled (true);
  Enable zoom Web Page feature Websettings.setsupportzoom (TRUE);
  Get Focus Webview.requestfocus ();
  To determine the network connection status, no network to set up the network, the network will continue String URL = constants.url;
  Webview.loadurl (URL); Webviewclient mainly help WebView handle various notifications, request events Webviewclient client = new Webviewclient () {/** * page load will callback this method, if the user agrees to obtain the successful Code * then sends an asynchronous POST request to get Access_token * If the Access_token information is successfully obtained, save all important information * and jump to the maininterface * @param View presentation interface * @param URL loading url * @param favicon URL of the relevant icon * * @Override public void Onpagest Arted (webview view, String URL, Bitmap favicon) {if (Url.startswith (Constants.redirect_url)) {String code = URL
     . Split ("=") [1];
     Set Request parameters Requestparams params = new Requestparams ();
     Params.put ("client_id", constants.client_id);
     Params.put ("Client_secret", Constants.app_secret);
     Params.put ("Grant_type", "Authorization_code");
     Params.put ("Redirect_uri", Constants.redirect_url);
     Params.put ("code", code); Sends an asynchronous POST request Access_token token and saves important information access_token such as Oathu//client_id and Client_secret and Weiborestclient.post ("oauth2/ Access_token ", params, new Asynchttpresponsehandler () {@Override public void onsuccess (int i, header[] Header
       s, byte[] bytes {String data = new string (bytes);
        try {//server returns Jsonobject object = new Jsonobject (data);
  (Preferences.edit ()). Clear ();      SaveData (object); Toast.maketext (Oauthactivity.this, "landing success", Toast.
        Length_short). Show ();
        Into the microblogging main interface Intent Intent = new Intent (oauthactivity.this,mainactivity.class);
        StartActivity (Intent);
       Turn off the Licensing interface OAuthActivity.this.finish ();
       catch (Jsonexception e) {e.printstacktrace (); @Override public void onfailure (int i, header[] headers, byte[] bytes, throwable throwable) {Toast
       . Maketext (Oauthactivity.this, "Landing failure", Toast.length_short). Show ();
      OAuthActivity.this.finish ();
  }});}}};
 Webview.setwebviewclient (client); /** * Use sharedpreferences saved Oathu client_id and Client_secret and access_token important information * * private void SaveData (Jsonobject o
   Bject) {try {sharedpreferences.editor Editor = Preferences.edit ();
   Editor.putstring ("Access_token", Object.getstring ("Access_token"));
   Editor.putstring ("Remind_in", Object.getstring ("remind_in")); Editor.putstring("Expires_in", Object.getstring ("expires_in"));
   Editor.putstring ("UID", object.getstring ("UID"));
   Editor.putstring ("client_id", constants.client_id);
   Editor.putstring ("Redirect_uri", Constants.redirect_url);
   Editor.putstring ("Client_secret", Constants.app_secret);
  Editor.apply ();
  catch (Jsonexception e) {e.printstacktrace ();
 } }}

Here the asynchronous request Class Weiborestclient.java, which uses asynchronous send HTTP requests, handles the response HTTP request process in the callback function without the UI thread using the thread pool to manage the concurrency number support Get/post request

public class Weiborestclient {
 private static final String Base_url = "https://api.weibo.com/";
 private static Asynchttpclient client = new Asynchttpclient ();
 public static void Get (String URL, requestparams params, Asynchttpresponsehandler responsehandler) {
  Client.get ( Getabsoluteurl (URL), params, responsehandler);
 public static void post (String URL, requestparams params, Asynchttpresponsehandler responsehandler) {
   client.post ( Getabsoluteurl (URL), params, responsehandler);
 private static string Getabsoluteurl (String relativeurl) {return
  base_url + relativeurl;
 }
}

The layout of the oauthactivity webview.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
    android:layout_width=" match_parent "
    android:layout_height=" match_parent ">

 < WebView
  android:id= "@+id/webview"
  android:layout_width= "match_parent"
  match _parent "/>
</LinearLayout>

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.