【新手入門篇】新浪微博應用開發之Java入門篇


新浪微博應用開發之Java篇

 

20121111日星期日

一、開發流程簡介:

1、  訪問http://open.weibo.com/注冊成為開發者

2、  在以下地址創建一個應用,假設創建一個桌面應用:

http://open.weibo.com/apps/new?sort=mobile

 

3、  進入管理中心,查看並記住應用ID和密碼:

 

 

4、  在“應用中心-高級信息”設置回調頁面(設置后一般需要半小時左右才能生效):

 

OK,准備工作完成!

二、不使用任何SDK實現Oauth授權並實現簡單的發布微博功能:

創建一個Java項目,編寫如下代碼,具體過程代碼中已寫的很清楚,這里不再做解釋:

注意先修改應用ID、應用密碼和回調頁面成你自己的!訪問授權頁面:

 

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 劉顯安
 * 不使用任何SDK實現新浪微博Oauth授權並實現發微薄小Demo
 * 日期:2012年11月11日
 */
public class Test
{
    static String clientId="2355065950";//你的應用ID
    static String clientSecret="72037e76bee00315691d9c30dd8a386a";//你的應用密碼
    static String redirectUri="https://api.weibo.com/oauth2/default.html";//你在應用管理中心設置的回調頁面
    
    public static void main(String[] args) throws Exception
    {
        testHttps();//測試
        //第一步:訪問授權頁面獲取授權
        System.out.println("請打開你的瀏覽器,訪問以下頁面,登錄你的微博賬號並授權:");
        System.out.println("https://api.weibo.com/oauth2/authorize?client_id="+clientId+"&response_type=code&redirect_uri="+redirectUri+"&forcelogin=true");
        //第二步:獲取AccessToken
        System.out.println("請將授權成功后的頁面地址欄中的參數code:");
        String code=new Scanner(System.in).next();
        getAccessToken(code);
        //第三步:發布一條微博
        System.out.println("請輸入上面返回的值中accessToken的值:");
        String accessToken=new Scanner(System.in).next();
        updateStatus("發布微博測試!來自WeiboDemo!", accessToken);
    }
    /**
     * 測試能否正常訪問HTTPS打頭的網站,
     */
    public static void testHttps()
    {
        try
        {
            trustAllHttpsCertificates();//設置信任所有的http證書
            URL url=new URL("https://api.weibo.com/oauth2/default.html");
            URLConnection con=url.openConnection();
            con.getInputStream();
            System.out.println("恭喜,訪問HTTPS打頭的網站正常!");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    /**
     * 以Post方式訪問一個URL
     * @param url 要訪問的URL
     * @param parameters URL后面“?”后面跟着的參數
     */
    public static void postUrl(String url,String parameters)
    {
        try
        {
            trustAllHttpsCertificates();//設置信任所有的http證書
            URLConnection conn = new URL(url).openConnection();
            conn.setDoOutput(true);// 這里是關鍵,表示我們要向鏈接里注入的參數
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());// 獲得連接輸出流
            out.write(parameters);
            out.flush();
            out.close();
            // 到這里已經完成了,開始打印返回的HTML代碼
            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();
        }
    }
    /**
     * 獲取AccessToken
     * @param code 在授權頁面返回的Code
     */
    public static void getAccessToken(String code)
    {
        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);
    }
    /**
     * 利用剛獲取的AccessToken發布一條微博
     * @param text 要發布的微博內容
     * @param accessToken 剛獲取的AccessToken
     */
    public static void updateStatus(String text,String accessToken)
    {
        String url="https://api.weibo.com/2/statuses/update.json";
        String parameters="status="+text+"&access_token="+accessToken;
        postUrl(url, parameters);
        System.out.println("發布微博成功!");
    }
    /**
     * 設置信任所有的http證書(正常情況下訪問https打頭的網站會出現證書不信任相關錯誤,所以必須在訪問前調用此方法)
     * @throws Exception
     */
    private static void trustAllHttpsCertificates() throws Exception
    {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        trustAllCerts[0] = new X509TrustManager()
        {
            @Override
            public X509Certificate[] getAcceptedIssuers()
            {
                return null;
            }
            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException
            {}
            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException
            {}
        };
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
}

訪問授權頁面:

授權成功:

 

發布微博成功:

 

控制台輸出結果:

 

三、使用weibo4j-oauth2這個SDK做一個簡單的搶沙發工具:

1、SDK下載:

http://code.google.com/p/weibo4j

下載下來是個包含測試代碼的整個SDK源代碼,可以打包成jar文件方便調用,我這里打包成名為weibo4j-oauth2.jar的文件,注意先修改config.properties文件中的應用id、應用密碼、回調頁面。

2、在項目中導入以下6個包:

 

3、使用WindowsBuild新建一個Jframe窗體,大體布局如下:

三個按鈕的事件分別如下:

public Date minTime;//最近一條微博的更新時間
    /**
     * 打開授權頁面
     */
    public void openUrl()
    {
        try
        {
            BareBonesBrowserLaunch.openURL(new Oauth().authorize("code"));
        }
        catch (WeiboException e)
        {
            e.printStackTrace();
        }
    }
    /**
     * 獲取當前登錄用戶的好友列表
     */
    public void getFriends()
    {
        try
        {
            //獲取好友列表
            accessToken=new Oauth().getAccessTokenByCode(textFieldCode.getText());
            Friendships friendships=new Friendships();
            friendships.setToken(accessToken.getAccessToken());
            for(User user:friendships.getFriendsByID(accessToken.getUid()).getUsers())
            {
                comboBox.addItem(user.getName());
            }
        }
        catch (WeiboException e)
        {
            e.printStackTrace();
        }
    }
    /**
     * 開始監控關注用戶的微博
     * @throws WeiboException 
     */
    public void start()
    {
        try
        {
            System.out.println("開始監控");
            Timeline timeline=new Timeline();
            timeline.setToken(accessToken.getAccessToken());
            minTime = timeline.getUserTimelineByName(comboBox.getSelectedItem().toString()).getStatuses().get(0).getCreatedAt();
            Timer timer=new Timer();
            timer.schedule(new TimerTask()
            {
                @Override
                public void run()
                {
                    try
                    {
                        Timeline timeline=new Timeline();
                        timeline.setToken(accessToken.getAccessToken());
                        Status status=timeline.getUserTimelineByName(comboBox.getSelectedItem().toString()).getStatuses().get(0);
                        if(status.getCreatedAt().after(minTime))//如果最新微博的發表時間在之前相對時間的后面
                        {
                            minTime=status.getCreatedAt();
                            System.out.println("你關注的用戶更新微博啦");
                            Comments comments=new Comments();
                            comments.setToken(accessToken.getAccessToken());
                            comments.createComment("哈哈,我來評論啦!", status.getId());
                            JOptionPane.showMessageDialog(null, "恭喜,搶沙發成功!");
                        }
                    }
                    catch (WeiboException e)
                    {
                        e.printStackTrace();
                    }
                }
            }, 0, 5000);//設置5秒鍾刷新一次
        }
        catch (WeiboException e)
        {
            e.printStackTrace();
        }
    }

項目源代碼下載地址:

http://download.csdn.net/detail/liuxianan612/4755895

整理后的SDK下載地址:

http://download.csdn.net/detail/liuxianan612/4755925

有問題可以聯系: 

微博:http://weibo.com/liuxianan

博客園:http://www.cnblogs.com/liuxianan/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM