工作笔记—新浪微博Oauth2.0授权 获取Access Token (java)

  java发送新浪微博,一下博客从注册到发布第一条微博很详细

利用java语言在eclipse下实现在新浪微博开发平台发微博http://blog.csdn.net/michellehsiao/article/details/7644796

新浪微博Oauth2.0授权 获取Access Token (java):http://blog.sina.com.cn/s/blog_6d34781a0101jerb.html

调用新浪微博API发布第一条微博(java版)http://blog.csdn.net/kobeguang/article/details/7643782

微信公众平台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。没法重定向了,如果有哪位大神看到后,知道怎么解决,望赐教!

没有办法,只能获取code,根据code获取access_token了

代码如下:

  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是有生命周期的

原文地址:https://www.cnblogs.com/kingxiaozi/p/4449618.html