Java uses Sina Weibo API to develop the basic method of microblogging application _java

Source: Internet
Author: User
Tags oauth

Sina Weibo API is now used more widely, do a complete development process demo
1, the first step of registration, do not say more, registered account and become a developer account, this step will not be the case, please immediately smash the computer unplug the network cable home farming.
2, the second step to create the application, the developer account to create a good, open Sina Weibo development platform: http://open.weibo.com
Above menu bar Click Last Admin Center

If it is a Web application, choose to create the application of the Web site access, and then according to the requirements of Sina Weibo Balabalabala own to do
Application creation completed. Click on the application Jump page, click to view the application parameters, you can see the application of the relevant parameters, these parameters will be used in the fourth step.
3, the third step to download the SDK, back to the top of the menu bar, click on the document, and then click on the left menu bar SDK, select the Java SDK, and then Balabala download, this step of the operation of the problem also please go home farming.

The so-called SDK is not the SDK (personally think the name is a bit misleading), but a can run the project, download after the decompression, and import to eclipse, you can see two directory src and example
SRC is part of Sina Weibo
Example is an example, the interface of the demo
4, the fourth step configuration parameters, find the config.properties under the SRC directory
The first three parameters need to be configured as parameters in the application parameters mentioned in the second step
The back is all the default, no need to change.
The first three parameters are configured as follows
client_id for App Key
Client_sercret for App Secret
Redirect_uri for OAuth2.0-Authorized callback URLs apply Information > Advanced Information >oauth2.0 Authorization settings The following authorization callback page this is a URL you've filled out to point to yourself. Server of course we can use any URL in the development phase As long as we can understand the process of OAuth authorization. Here we enter a http://www.baidu.com Cancel authorization callback page also note that the string of URLs here must be consistent
5, the fifth step to obtain accesstoken, under normal circumstances Accesstoken acquisition is required to pass OAuth2.0 authentication, but in order to be simpler I first say a simple method. I'll talk about OAuth2.0 later.
or select the top menu bar document >API>API Test Tool
Select the application you created click to get Accesstoken the text box below is what we want Accesstoken

6, the sixth step first to do an interface instance
Go to the microblogging API to find an existing interface,
I've been randomly looking for a user-posted microblogging statuses/user_timeline for testing.

Click on this interface to view the details of this interface, you can see the interface of each incoming parameter and return parameters this needless to say.

Implement OAuth authorization without using any SDK and implement a simple release microblogging function:
Create a Java project, write the following code, which is clearly written in the process code, no longer explained here:

Note Modify the application ID, apply password, and callback page first to your own! Access Authorization page:

Package com;
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.net.URL;
Import java.net.URLConnection;
Import java.security.cert.CertificateException;
Import Java.security.cert.X509Certificate;

Import Java.util.Scanner;

Import Javax.net.ssl.X509TrustManager; /** * @author Liu Xianhan * Do not use any SDK to implement Sina Weibo OAuth authorization and realize a small demo * Date: November 11, 2012/public class Test {static String clientid= "2355065950"//Your Application id static string clientsecret= "72037e76bee00315691d9c30dd8a386a";//Your application password is static string Redirecturi= "https://api.weibo.com/oauth2/default.html"; the callback page that you set up in Application Management Center public static void Main (string[] args) thr
    oWS Exception {Testhttps ()///First step: Access Authorization page to obtain authorization System.out.println ("Please open your browser, visit the following page, login to your Weibo account and authorize:"); System.out.println ("https://api.weibo.com/oauth2/authorize?client_id=" +clientid+) &response_type=code&
    Redirect_uri= "+redirecturi+" &forcelogin=true "); Step two: Get Accesstoken SYSTEM.OUT.PRINTLN ("Please code the parameters in the page address bar of the successful authorization:");
    String code=new Scanner (system.in). Next ();
    Getaccesstoken (code);
    Step three: Publish a microblog System.out.println ("Enter the value in the value returned above accesstoken:");
    String accesstoken=new Scanner (system.in). Next (); UpdateStatus ("Release micro-BO test!") From weibodemo!
  ", Accesstoken); /** * Test for normal access to HTTPS-preceded Web site,/public static void Testhttps () {try {trustallhttpscertificates (
      ;/Set Trust all HTTP certificate url url=new URLs ("https://api.weibo.com/oauth2/default.html");
      URLConnection con=url.openconnection ();
      Con.getinputstream (); System.out.println ("Congratulations, visit HTTPS the beginning of the site normal!"
    ");
    catch (Exception e) {e.printstacktrace (); }/** * post-access URL * @param URL to be accessed * @param parameters URL behind "? "followed by the parameter */public static void PostURL (String url,string parameters) {try {trustallhttpscertificate
      s ();/setting trusts all HTTP certificates urlconnection conn = new URL (URL). OpenConnection (); Conn.setdooutput (TRUE);// Here is the key, indicating that the parameter we want to inject into the link outputstreamwriter out = new OutputStreamWriter (Conn.getoutputstream ());//Get the connection output stream OUT.W
      Rite (parameters);
      Out.flush ();
      Out.close ();
      It's done here, start printing the returned HTML code bufferedreader reader = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));
      String line = null;
      while (line = Reader.readline ())!= null) {System.out.println (line);
    } catch (Exception e) {e.printstacktrace ();
    /** * Gets the code/public static void Getaccesstoken (String code) {Accesstoken * @param code returned on the authorization page
    String url= "Https://api.weibo.com/oauth2/access_token"; String parameters= "client_id=" +clientid+ "&client_secret=" +clientsecret+ "&grant_type=authorization_code"
    + "&redirect_uri=" +redirecturi+ "&code=" +code;
  PostURL (URL, parameters);
  /** * Using the newly acquired Accesstoken to publish a micro-blog * @param text to be published microblogging content * @param accesstoken just acquired Accesstoken * *public static void UpdateStatus (String text,string accesstoken) {string url= Https://api.weibo.com/2/statuses/updat
    E.json ";
    String parameters= "status=" +text+ "&access_token=" +accesstoken;
    PostURL (URL, parameters); System.out.println ("Publish Weibo success!")
  ");  /** * Settings Trust all HTTP certificates (a site that normally has the first access to HTTPS will receive a certificate distrust-related error, so this method must be called before accessing) * @throws Exception/private static void Trustallhttpscertificates () throws Exception {javax.net.ssl.trustmanager[] trustallcerts = new Javax.net.ssl.Trust
    MANAGER[1];
      Trustallcerts[0] = new X509trustmanager () {@Override public x509certificate[] Getacceptedissuers ()
      {return null; @Override public void checkservertrusted (x509certificate[] arg0, String arg1) throws Certificateex ception {} @Override public void checkclienttrusted (x509certificate[] arg0, String arg1) throw
    S certificateexception {}}; Javax.net.ssl.SSLContext sc = JAVAx.net.ssl.SSLContext.getInstance ("SSL");
    Sc.init (NULL, trustallcerts, NULL);
  Javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory (Sc.getsocketfactory ());

 }
}

Access Authorization page:

Authorized success:

Publish Weibo success:

Console output Results:

Related Article

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.