Although Sina Weibo open platform provides development SDK downloads in various languages, each comes with some demo and interface description documents for basic interface calls. However, after trying patiently these days, I feel that the introduction guidance on Sina Weibo’s open platform is somewhat inconsistent with the demo usage annotations in the downloaded Java development package weibo4j package. In addition, my own understanding ability is limited, which leads to many inconspicuous problems. Fortunately, I didn't give up trying to understand it. Less nonsense, the following is my learning process.
If you want to develop your own Weibo application by calling the Sina Weibo Open Platform API, the first step is to have a sina Weibo account and a CSDN account, because we need to use these two accounts to create Weibo applications at the same time to obtain App key and Secret key. So what are the uses of App key and Secret key?
In fact, I just read a series of explanations on the open platform of Sina Weibo, but I didn’t understand how the App key and Secret key are useful. Because the more important thing is to understand the entire process of OAuth authentication and authorization, as well as the role of several tokens and 4 URLs in the entire OAuth authentication and authorization process.
When I first met OAuth, which had no idea, I thought I would be unable to continue learning. Fortunately, I found the following articles, which are very helpful for understanding OAuth. The link is as follows:
There are 3 participants in OAuth, namely User, Service Provider, and Consumer. Suppose I want to develop an application (App) based on the Sina Weibo open platform for other Sina Weibo users to use. Their correspondence is as follows:
In fact, our App is equivalent to a third-party application for User and Provider (sina Weibo platform). As a third-party App, if you want to access the resources saved by User on the sina Weibo platform, you must undergo a series of authentication and authorization before it can work.
The following is a diagram based on my understanding of the entire OAuth authentication and authorization process (you can take a look and skip it. After you have a certain understanding of some of the concepts below, you will look back at this flow chart):
Combining the flowchart above, here is my understanding of these terms and description of each process:
Consumer key and Consumer Secret: The open platforms on sina Weibo are called App key and Secret key respectively. Consumer applies to Provider to be able to call its open API. After the application is approved, the Provider will be assigned to the Consumer that meets its requirements, which is used to uniquely identify that the Consumer meets the Provider's requirements.
Corresponding to flows 1 and 2 in the figure above.
Request Token, Request Secret: When the User accesses the Consumer and wants to obtain its special service, the Service is returned by the Consumer after integrating the resources stored in the User itself. At this time, the Consumer requests the Provider to obtain a Request Token, which is used to uniquely identify the specific association between the Consumer and the User.
Corresponding to flows 3, 4, and 5 in the figure above.
To process 6, the Consumer must direct the User to the OAuth authentication and authorization page provided by the Provider. In fact, the browser redirects to the authenticationURL with the Request Token and Request Secret parameters attached. This URL is provided by Provider.
Next, in process 7 and 8, the User authorizes the Consumer (usually just log in by entering the account and password), the Provider will redirect to the Callback_URL provided by the Consumer in process 1, and attaches OAuth Token and OAuth Verifier to the URL parameters.
Process 9 is the Consumer requesting Provider again to obtain Access Token through the Request Token that has been obtained from Provider before.
Access Token, Access Secret: If the Provider returns an Access Token without User authorization in Process 10, it is used to uniquely identify the resources and information stored in the Provider of a certain Consumer. Then Consumer can start using the obtained Access Token and Access Secret to access the resources stored in the Provider by the corresponding User.
After integrating and operating the User information in Process 11, the specific service results can be returned to the User.
Through the above understanding of the OAuth process, we know that User has not leaked the account, password, etc. required to log in to the provider to the third-party Consumer. At the same time, the User can use the Consumer's special services. What a clever and safe operation process!
In addition, in the figure above, Consumer has made different requests from Provider. In fact, Provider provides 3 URLs with different functions to Consumer access. Screenshots of these 3 URLs in the sina Weibo open platform are as follows:
Use OAuth verification and post on sina Weibo open platform
To use the API of the Sina Weibo open platform, you should first obtain the App key and App Secret assigned by Sina. Below are the App key and App Secret assigned by Sina after I created the application (this must be kept confidential).
Then download the Weibo SDK, I use weibo4j in Java.
Modify the App Key and App Secret of the Weibo.java class in the SDK package to the App Key and App Secret you just obtained, as shown in the following instructions for use:
After completing these, you can start writing code based on the provided demo. as follows:
WebOAuth.java is used to initialize the App Key and App Secret required for the Weibo.java class, and provides methods to getRequestToken() and gettAccessToken() to obtain RequestToken and Access Token. The required parameters are shown in the code. In addition, a method to publish a text Weibo is also provided to update().
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 authentication public class WebOAuth { private Weibo weibo; public WebOAuth(){ // Prepare Consumer Key and Consumer Secret // Corresponding to Sina Weibo application is the App you applied for key and Secret key System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY); System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET); weibo = new Weibo(); } // Get request token public RequestToken according to the incoming callback_url public RequestToken getRequestToken(String backUrl) { try { // Specify callback_url and get 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("Exception occurred when getting the Request token!"); e.printStackTrace(); return null; } } // Get access token public based on the incoming request token and verifier AccessToken gettAccessToken(RequestToken requestToken, 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("Exception occurred when getting Access token!"); e.printStackTrace(); return null; } } // Post Weibo based on the incoming Access Token and content public void update(AccessToken access, String content) { try { weibo.setToken(access.getToken(), access.getTokenSecret()); content = new String(content.getBytes("GBK"), "UTF-8"); Status status = weibo.updateStatus(content); System.out.println("Successfully posted on Weibo: " + status.getText() + "."); } catch (UnsupportedEncodingException e) { System.out.println("Exception occurred when Weibo content converted to encoding!"); e.printStackTrace(); } catch (WeiboException e) { System.out.println("Exception occurred when Weibo posting an exception!"); e.printStackTrace(); } } } request.jsp is used to provide callback_url (here we customize it as callback.jsp in the following). After obtaining the RequestToken, save the RequestToken into the Session and redirect the page to callback.jsp for verification and 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:useBean id="weboauth" scope="session" /> <% if("1".equals(request.getParameter("opt"))) { // Pass in 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 with the callback_url callback address attached to the response.sendRedirect(url); }else{ out.println("request error"); } }else{ %> <a href="request.jsp?opt=1">Please click on OAuth authentication in the web method! </a> <% } %>
callback.jsp. After redirecting in the previous step, the oauth_verifier parameter will be attached to the callback_url. At this time, we apply to obtain the AccessToken based on the RequestToken saved in the Session and the obtained oauth_verifier parameter. Once AccessToken is obtained, we redirect the page to writeWeibo.html, the page that writes Weibo.
<%@ page contentType="text/html;charset=utf-8" %> <%@ page language="java" import="weibo4j.http.*" %> <%@ page language="java" import="weibo4j.*" %> <jsp:useBean id="weboauth" scope="session" /> <% // Get the oauth_verifier parameter in HTTP request String verifier=request.getParameter("oauth_verifier"); 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("5 Go to writeWeibo.html"); 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, a very simple HTML file. <html> <head><title>Posted sina Weibo</title></head> <body bgcolor="#d0d0d0" > <form action="updateWeibo.jsp" method="post"> Please write text within 140 characters here:</br> <textarea name="weiboText" rows="3" cols="30">Test Sina Weibo! </textarea></br> <input type="submit" value="Publish"> <input type="reset" value="clear"></br> </form> </body> </html> updateWeibo.jsp, used to post text Weibo, that is, to call the update method in WebOAuth.java. <%@ page contentType="text/html;charset=utf-8" %> <%@ page language="java" import="weibo4j.http.*" %> <%@ page language="java" import="weibo4j.*" %> <jsp:useBean id="weboauth" scope="session" /> <% AccessToken accessToken = (AccessToken)session.getAttribute("accessToken"); String weiboText = (String)request.getParameter("weiboText"); // Continuous posting of the same Weibo content will return 400 errors weboauth.update(accessToken, weiboText); out.println("WeiboText published successfully!"); %>
Before running, we need to prepare Tomcat and put the above source file into the correct directory. In addition, you should also add the commons-httpclient-3.1.jar package in the SDK package in the /WEB-INF/lib directory, as well as the weibo4j.jar I compiled and packaged myself (which is the specific Java implementation in the sina Weibo open platform).
Run Tomcat and access the request.jsp page in your browser, as shown in the figure below:
Click the link in it, as shown in the figure below (note the changes in 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 and valid sina Weibo account and password and authorize it. The following are the results of filling in my Weibo account for testing and authorizing it:
The URL of the address bar is as follows:
http://localhost:8080/sinaweibo/writeWeibo.html
Click "Publish", as shown below:
Log in to Weibo to view it, as shown below:
Check out the list of applications authorized by this account:
At this point, it is probably this process about OAuth method to use the sina Weibo open platform to post Weibo.
summary:
1. In fact, there are still many details that I haven’t mentioned. I have tried many times before I discovered the problem, understood the problem, and then solved the problem;
2. If the cookies for our login to Sina Weibo account information have been saved in the browser, then you do not need to enter the account information when authorizing it. Of course, you can also modify it without using the current account for authorization;
3. There are also some information entered by the console, such as Token, URL, and server return information, which are not given in screenshots.