Tutorials for sending tweets using Java through the OAuth protocol _java

Source: Internet
Author: User
Tags http request oauth

Although the Sina Weibo open platform provides a variety of language versions of the development SDK download, but also each attached to some basic interface calls Demo and interface documentation. But after a few days of patient experimentation, it feels a bit inconsistent to feel the introductory guidance on Sina Weibo's open platform and the Demo used in the Java development package WEIBO4J package that was downloaded. Coupled with the limited understanding of their own, resulting in a lot of difficult to touch the mind. But fortunately did not give up to try to understand it. Less nonsense, the following is the process of my study.

To develop your microblog application by calling the Sina Weibo open platform API, the first step is to have Sina Weibo account and csdn account, because we have to use both accounts to create microblogging applications, to obtain the APP key and Secret key. What's the use of APP key and Secret key?

In fact, I simply read the Sina Weibo open platform of a series of instructions do not understand what the app key and Secret key is used. Because more emphasis is must understand OAuth authentication, the entire process of authorization, as well as in the entire OAuth authentication, authorization process several Token, 4 URLs role.

Just start to encounter completely no concept of the OAuth, think it will not go to study. Fortunately, the following articles are found to be very helpful for understanding OAuth links as follows:

    • Introduction to OAuth protocol
    • Java application programming based on OAuth security protocol
    • Using OAuth in Twitter applications

There are 3 participants in the OAuth, namely User, Service Provider, Consumer. Let's say I'm developing an app based on the Sina Weibo open platform for use by other Sina Weibo users. Their corresponding relationship is as follows:

    • User => wants to use this app's Sina Weibo users
    • Provider => Sina Micro Bo open Platform
    • Consumer => App

In fact, our App is equivalent to a third-party application for User and Provider (Sina Weibo platform). As a third party App that wants to access the resources stored in the Sina microblogging platform, the user must pass through a series of certifications and authorizations before it can work.


The following is based on my understanding of the entire OAuth certification, authorization process to draw a picture (you can see skip, when some of the following concepts have a certain understanding and then look back to this flowchart):

In combination with the above flowchart, here is my understanding of these terms and the description of each process:
Consumer Key, Consumer Secret: In Sina Weibo open platform is called App key, Secret key respectively. Consumer to the Provider request to be able to invoke its open API, after the request is passed by Provider assigned to meet its requirements Consumer, used to uniquely identify the Consumer meet the requirements of Provider.
Corresponds to the processes 1 and 2 above.

Request Token, request Secret: When the user accesses Consumer and wants to be able to obtain its special service, the service is returned after the Consumer consolidates the resources that the user itself holds in Provider. At this point, Consumer obtains the Requst Token to the Provider request, which uniquely identifies the Consumer to a specific association with that User.
Corresponds to the process 3, 4, 5 of the diagram above.

To process 6, Consumer must lead the User to the OAuth authentication and authorization page provided by provider, in fact, the browser redirects to the Secret with the request Token and request Authenticationurl parameters attached 。 The URL is provided by Provider.

Next in Process 7 and 8, User authorizes the Consumer (typically by entering account number, password login), then Provider is redirected to the Callback_url provided in Process 1, and the URL parameter is appended with OAuth Token and OAuth Verifier.

Process 9 is Consumer to request Provider again to obtain access Token by requesting Token, which was previously obtained from Provider.

Access Token, Access Secret: If process 10 Provider returns an access Token that is not authorized by the user, it is used to uniquely identify a specific Consumer that can access a user for storage in Provider of resources, information. Then Consumer can start using the Access Token and access Secret to access the resources that correspond to the User's stored in Provider.
After the integration and operation of the user information in process 11, a specific service result can be returned to user.

Through the above for the OAuth process understanding, we know that in fact, User does not have their own login Provider required account, password, etc. leaked to the third party Consumer. At the same time, user can use the special service of Consumer. This is a very clever and safe operation of the process Ah!
In addition, the above Consumer has 3 times and Provider issued a different request, in fact, is provided by the Provider to provide 3 different roles of the URL to Consumer access. The screenshot of these 3 URLs in the Sina Weibo open platform is as follows:

Sina Weibo open platform uses OAuth to authenticate and publish Weibo
to use the Sina Weibo open platform API, you should first get the app key and app Secret that Sina allocates, and the following is the app key and app Secret that Sina assigns after I created the app (this is confidential.)

Then download the microblogging SDK, I use Java weibo4j.
Modify the Weibo.java class's app key and app Secret in the SDK pack for the app key and app Secret just acquired, as illustrated in the following illustration:

After you have done this, you can start writing code based on the demo provided. As follows:
Weboauth.java, which is used to initialize the app Key and app Secret required for the Weibo.java class, and provides methods for obtaining request Token and Access Token Getrequesttoken (), Gettaccesstoken () with the required parameters as shown in the code. In addition, a method of publishing a text microblog update () is also provided.

Package weibo4j.examples; Import weibo4j. 
Status; Import weibo4j. 
Weibo; Import weibo4j. 
Weiboexception; 
Import Weibo4j.http.AccessToken; 
Import Weibo4j.http.RequestToken; 
 
Import java.io.UnsupportedEncodingException; 
 
  Web Mode Authentication public class Weboauth {private Weibo Weibo; Public Weboauth () {//Ready Consumer key, Consumer Secret//corresponding to Sina Weibo application is the app key and Secret key System.set 
    Property ("Weibo4j.oauth.consumerKey", Weibo.consumer_key); 
    System.setproperty ("Weibo4j.oauth.consumerSecret", Weibo.consumer_secret); 
  Weibo = new Weibo (); Callback_url GET request Token public Requesttoken Getrequesttoken (String backurl) {try {/ 
 
      /designate Callback_url and obtain request token Requesttoken Requesttoken = Weibo.getoauthrequesttoken (Backurl); 
      System.out.println ("Request token:" + requesttoken.gettoken ()); 
 
      System.out.println ("Request token secret:" + Requesttoken.gettokensecret ()); return requesttoken; 
    catch (Exception e) {System.out.println ("Get request token an exception!") 
      "); 
      E.printstacktrace (); 
    return null; Verifier access token public accesstoken Gettaccesstoken (Requesttoken Requestto by incoming request token and 
          Ken, String Verifier) {try {Accesstoken Accesstoken = Weibo.getoauthaccesstoken (requesttoken 
       
      . GetToken (), Requesttoken.gettokensecret (), verifier); 
      System.out.println ("Access token:" + accesstoken.gettoken ()); 
 
      System.out.println ("Access token secret:" + Accesstoken.gettokensecret ()); 
    return accesstoken; catch (Exception e) {System.out.println ("Get access token exception!") 
      "); 
      E.printstacktrace (); 
    return null; Token and content published microblogging public void update (Accesstoken access, String content) {try {we 
      Ibo.settoken (Access.gettoken (), Access.gettokensecret ()); 
Content = new String (content.getbytes ("GBK"), "UTF-8");      Status status = Weibo.updatestatus (content); 
    System.out.println ("Published Weibo successfully:" + status.gettext () + "."); catch (Unsupportedencodingexception e) {System.out.println ("microblogging content transcoding exception!") 
      "); 
    E.printstacktrace (); catch (Weiboexception e) {System.out.println ("published Weibo exception!) 
      "); 
    E.printstacktrace (); }} request.jsp, used to provide callback_
URL (we customize this here to the callback.jsp below), after obtaining the Requesttoken, save the Requesttoken into session and redirect the page to callback.jsp for authentication, authorization.  <%@ page contenttype= "text/html;charset=utf-8"%> <%@ page language= "java" import= "weibo4j.*"%> <%@ page Language= "java" import= "weibo4j.http.*"%> <%@ page language= "java" import= "weibo4j.util.*"%> <jsp:useBe An id= "Weboauth" scope= "session" class= "Weibo4j.examples.WebOAuth"/> <% if ("1". Equals (Request.getparameter ("O 
    PT ")) {//incoming callback_url String callback_url =" http://localhost:8080/sinaweibo/callback.jsp "; Requesttoken Requesttoken = WEBOAUTH.GEtrequesttoken (Callback_url); 
      if (Requesttoken!= null) {out.println (Requesttoken.gettoken ()); 
      Out.println (Requesttoken.gettokensecret ()); 
 
      Session.setattribute ("Requesttoken", Requesttoken); 
      String URL = requesttoken.getauthorizationurl () + "&oauth_callback=" +callback_url; 
 
      System.out.println ("Authorizationurl:" + URL); 
      Barebonesbrowserlaunch.openurl (Callback_url); 
 
      Response.sendredirect (Requesttoken.getauthorizationurl ()); 
    Redirect to the Sina Weibo authentication page response.sendredirect (URL) with the Callback_url callback address attached; 
    }else{out.println ("request Error"); }else{%> <a href= "Request.jsp?opt=1" > Please click on the Web Way OAuth certification! 
 </a> <%}%>

&NBSP
Callback.jsp, after redirection in the previous step, the Oauth_verifier parameter is appended to the Callback_url, which is then based on the The Requesttoken in session and the Oauth_verifier parameters obtained are requested to obtain accesstoken. Once we get the Accesstoken, we redirect the page to the writeweibo.html page where we write the microblog.

<%@ page contenttype= "text/html;charset=utf-8"%> <%@ page language= "java" import= "weibo4j.http.*"%> <% @ Page language= "java" import= "weibo4j.*"%> <jsp:usebean id= "Weboauth" session "Scope=" class=. 
 
  Weboauth "/> <%//Get the Oauth_verifier parameter String verifier=request.getparameter (" Oauth_verifier ") in the HTTP request; 
  Out.println ("Oauth_verifier:" +verifier); 
 
  System.out.println ("Oauth_verifier:" +verifier); 
 
    if (verifier!= null) {Requesttoken Requesttoken = (requesttoken) session.getattribute ("Requesttoken"); 
 
      if (Requesttoken!= null) {Accesstoken Accesstoken = Weboauth.gettaccesstoken (requesttoken,verifier);           
 
          if (Accesstoken!= null) {try{Session.setattribute ("Accesstoken", Accesstoken); 
          Out.println ("Turn to writeweibo.html in 5 Seconds"); 
          Thread.Sleep (5000); 
 
        Response.sendredirect ("http://localhost:8080/sinaweibo/writeWeibo.html"); }catch (exception e) {e.printstacktrace (); 
      }}else{out.println ("Access token request Error"); 
    }}else{out.println ("Request token session error"); 
  }}else{out.println ("Verifier String error");
%> writeweibo.html, very simple HTML file.  


Before running, we have to prepare Tomcat and put the above source files in the correct directory. In addition, you should add the Commons-httpclient-3.1.jar package in the SDK package to the \web-inf\lib directory, as well as my own compiled, packaged Weibo4j.jar (which is a concrete Java implementation in the Sina Weibo open platform).

Run Tomcat and access the request.jsp page in the browser, as shown in the following figure:

Click on the link, as shown below (note changes to the Address bar):

The URL of the address bar is as follows:
Http://api.t.sina.com.cn/oauth/authorize?oauth_token=efda6f2499877d0e6d814f8c3d31a1d1&oauth_callback=http ://localhost:8080/sinaweibo/callback.jsp

Fill in the specific valid Sina Weibo account number, password and authorization. Here are the results of the Weibo account that I tested and authorized:

The URL of the address bar is as follows:
Http://localhost:8080/sinaweibo/writeWeibo.html

Click "Publish", as shown below:

Log in to the micro-blog to view the following figure:

Check out the list of applications authorized by this account:

This is probably the process of using the Sina Weibo open platform to publish Weibo on the OAuth approach.

Summary:
1, in fact, there are a lot of details can not be mentioned, I have tried many times just a little bit to find the problem, understand the problem, then to solve the problem;
2, if the browser has saved our login Sina Weibo account information cookies, then the authorization does not enter the account information, of course, you can modify the current account without authorization;
3, there are some information entered by the console, such as token, URL, server return information is not given a screenshot.

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.