工做筆記—新浪微博Oauth2.0受權 獲取Access Token (java)

  java發送新浪微博,一下博客從註冊到發佈第一條微博很詳細html

利用java語言在eclipse下實如今新浪微博開發平臺發微博http://blog.csdn.net/michellehsiao/article/details/7644796java

新浪微博Oauth2.0受權 獲取Access Token (java):http://blog.sina.com.cn/s/blog_6d34781a0101jerb.htmljson

調用新浪微博API發佈第一條微博(java版)http://blog.csdn.net/kobeguang/article/details/7643782api

微信公衆平臺API的Java通信實現http://www.oschina.net/code/snippet_218887_22896瀏覽器

新浪微博APIhttp://open.weibo.com/wiki/%E9%A6%96%E9%A1%B5微信

 

以前從代碼是根據下面寫的,來獲取AccessToken微信公衆平臺

 1 你要是有用戶名/密碼,咋整都行。。。無非就是模擬成用戶正常登陸的樣子,而後就能活的accessToken了,算了,附上代碼。若是新浪的頁面改動的話須要從新修改代碼 
 2   
 3 public static AccessToken refreshToken(){ 
 4                  Properties props = new Properties(); 
 5                  try { 
 6                          props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("sina_account.properties")); 
 7                          String url = props.getProperty("url");/*模擬登陸的地址,https://api.weibo.com/oauth2/authorize*/ 
 8                          PostMethod postMethod = new PostMethod(url); 
 9                          postMethod.addParameter("client_id", props.getProperty("client_id"));//your client id 
10                          postMethod.addParameter("redirect_uri", props.getProperty("redirect_uri"));//your url 
11                          postMethod.addParameter("userId", props.getProperty("userId"));//須要獲取微薄的use id 
12                          postMethod.addParameter("passwd", props.getProperty("passwd")); 
13                          postMethod.addParameter("isLoginSina", "0"); 
14                          postMethod.addParameter("action", "submit"); 
15                          postMethod.addParameter("response_type", props.getProperty("response_type"));//code 
16                          HttpMethodParams param = postMethod.getParams(); 
17                          param.setContentCharset("UTF-8"); 
18                          List<Header> headers = new ArrayList<Header>(); 
19                          headers.add(new Header("Referer", "https://api.weibo.com/oauth2/authorize?client_id=your_client_id&redirect_uri=your_redirect_url&from=sina&response_type=code"));//僞造referer 
20                          headers.add(new Header("Host", "api.weibo.com")); 
21                          headers.add(new Header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0")); 
22                          HttpClient client  = new HttpClient(); 
23                          client.getHostConfiguration().getParams().setParameter("http.default-headers", headers); 
24                          client.executeMethod(postMethod); 
25                          int status = postMethod.getStatusCode(); 
26                          if(status != 302){ 
27                                  LOG.error("refresh token failed"); 
28                                  return null; 
29                          } 
30                          Header location = postMethod.getResponseHeader("Location"); 
31                          if(location != null){ 
32                                  String retUrl = location.getValue(); 
33                                  int begin = retUrl.indexOf("code="); 
34                                  if(begin != -1){ 
35                                          int end = retUrl.indexOf("&", begin); 
36                                          if(end == -1) 
37                                                  end = retUrl.length(); 
38                                          String code = retUrl.substring(begin+5, end); 
39                                          if(code != null){ 
40                                                          AccessToken token = oauth.getAccessTokenByCode(code); 
41                                                          Oauth oauth = new Oauth(); 
42                                                          return token; 
43                                          } 
44                                  } 
45                          } 
46                  } catch (FileNotFoundException e) { 
47                          LOG.error("error" + e); 
48                  } catch (IOException e) { 
49                          LOG.error("error" + e); 
50                  } 
51                  LOG.error("refresh token failed"); 
52                  return null; 
53          } 

如今程序報:200。無法重定向了,若是有哪位大神看到後,知道怎麼解決,望賜教!eclipse

 

沒有辦法,只能獲取code,根據code獲取access_token了post

代碼以下:測試

  1 import java.io.BufferedReader;
  2 import java.io.InputStreamReader;
  3 import java.io.OutputStreamWriter;
  4 import java.net.URL;
  5 import java.net.URLConnection;
  6 import java.security.cert.CertificateException;
  7 import java.security.cert.X509Certificate;
  8 import java.util.Scanner;
  9 
 10 import javax.net.ssl.X509TrustManager;
 11 
 12 /**
 13  * @author 劉顯安
 14  * 不使用任何SDK實現新浪微博Oauth受權並實現發微薄小Demo
 15  * 日期:2012年11月11日
 16  */
 17 public class Test
 18 {
 19     static String clientId="xxxxxx";//你的應用ID
 20     static String clientSecret="xxxxxxxxxxxxxxxxxxxxxxx";//你的應用密碼
 21     static String redirectUri="www.baidu.com";//你在應用管理中心設置的回調頁面
 22     
 23     public static void main(String[] args) throws Exception
 24     {
 25         testHttps();//測試
 26         //第一步:訪問受權頁面獲取受權
 27         System.out.println("請打開你的瀏覽器,訪問如下頁面,登陸你的微博帳號並受權:");
 28         System.out.println("https://api.weibo.com/oauth2/authorize?client_id="+clientId+"&response_type=code&redirect_uri="+redirectUri+"&forcelogin=true");
 29         //第二步:獲取AccessToken
 30         System.out.println("請將受權成功後的頁面地址欄中的參數code:");
 31         String code=new Scanner(System.in).next();
 32         getAccessToken(code);
 33         //第三步:發佈一條微博
 34         System.out.println("請輸入上面返回的值中accessToken的值:");
 35         String accessToken=new Scanner(System.in).next();
 36         updateStatus("發佈微博測試!來自WeiboDemo!", accessToken);
 37     }
 38     /**
 39      * 測試可否正常訪問HTTPS打頭的網站,
 40      */
 41     public static void testHttps()
 42     {
 43         try
 44         {
 45             trustAllHttpsCertificates();//設置信任全部的http證書
 46             URL url=new URL("https://api.weibo.com/oauth2/default.html");
 47             URLConnection con=url.openConnection();
 48             con.getInputStream();
 49             System.out.println("恭喜,訪問HTTPS打頭的網站正常!");
 50         }
 51         catch (Exception e)
 52         {
 53             e.printStackTrace();
 54         }
 55     }
 56     /**
 57      * 以Post方式訪問一個URL
 58      * @param url 要訪問的URL
 59      * @param parameters URL後面「?」後面跟着的參數
 60      */
 61     public static void postUrl(String url,String parameters)
 62     {
 63         try
 64         {
 65             trustAllHttpsCertificates();//設置信任全部的http證書
 66             URLConnection conn = new URL(url).openConnection();
 67             conn.setDoOutput(true);// 這裏是關鍵,表示咱們要向連接裏注入的參數
 68             OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());// 得到鏈接輸出流
 69             out.write(parameters);
 70             out.flush();
 71             out.close();
 72             // 到這裏已經完成了,開始打印返回的HTML代碼
 73             BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
 74             String line = null;
 75             while ((line = reader.readLine()) != null)
 76             {
 77                 System.out.println(line);
 78             }
 79         }
 80         catch (Exception e)
 81         {
 82             e.printStackTrace();
 83         }
 84     }
 85     /**
 86      * 獲取AccessToken
 87      * @param code 在受權頁面返回的Code
 88      */
 89     public static void getAccessToken(String code)
 90     {
 91         String url="https://api.weibo.com/oauth2/access_token";
 92         String parameters="client_id=" +clientId+"&client_secret=" +clientSecret+
 93             "&grant_type=authorization_code" +"&redirect_uri=" +redirectUri+"&code="+code;
 94         postUrl(url, parameters);
 95     }
 96     /**
 97      * 利用剛獲取的AccessToken發佈一條微博
 98      * @param text 要發佈的微博內容
 99      * @param accessToken 剛獲取的AccessToken
100      */
101     public static void updateStatus(String text,String accessToken)
102     {
103         String url="https://api.weibo.com/2/statuses/update.json";
104         String parameters="status="+text+"&access_token="+accessToken;
105         postUrl(url, parameters);
106         System.out.println("發佈微博成功!");
107     }
108     /**
109      * 設置信任全部的http證書(正常狀況下訪問https打頭的網站會出現證書不信任相關錯誤,因此必須在訪問前調用此方法)
110      * @throws Exception
111      */
112     private static void trustAllHttpsCertificates() throws Exception
113     {
114         javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
115         trustAllCerts[0] = new X509TrustManager()
116         {
117             public X509Certificate[] getAcceptedIssuers()
118             {
119                 return null;
120             }
121             public void checkServerTrusted(X509Certificate[] arg0, String arg1)
122                     throws CertificateException
123             {}
124             public void checkClientTrusted(X509Certificate[] arg0, String arg1)
125                     throws CertificateException
126             {}
127         };
128         javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
129         sc.init(null, trustAllCerts, null);
130         javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
131     }
132 }

  其實我也挺不喜歡拿來主義的,不過實在沒有版辦法,在這裏要感謝劉哥了,雖然我們未曾相識,在這裏仍是要好好感謝!

 

  根據上面的代碼獲取了access_token,可是token是有生命週期的

 

相關文章
相關標籤/搜索