工作笔记—新浪微博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
新浪微博API:http://open.weibo.com/wiki/%E9%A6%96%E9%A1%B5
之前从代码是根据下面写的,来获取AccessToken
你要是有用户名/密码,咋整都行。。。无非就是模拟成用户正常登录的样子,然后就能活的accessToken了,算了,附上代码。如果新浪的页面改动的话需要重新修改代码
public static AccessToken refreshToken(){
Properties props = new Properties();
try {
props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("sina_account.properties"));
String url = props.getProperty("url");/*模拟登录的地址,https://api.weibo.com/oauth2/authorize*/
PostMethod postMethod = new PostMethod(url);
postMethod.addParameter("client_id", props.getProperty("client_id"));//your client id
postMethod.addParameter("redirect_uri", props.getProperty("redirect_uri"));//your url
postMethod.addParameter("userId", props.getProperty("userId"));//需要获取微薄的use id
postMethod.addParameter("passwd", props.getProperty("passwd"));
postMethod.addParameter("isLoginSina", "0");
postMethod.addParameter("action", "submit");
postMethod.addParameter("response_type", props.getProperty("response_type"));//code
HttpMethodParams param = postMethod.getParams();
param.setContentCharset("UTF-8");
List<Header> headers = new ArrayList<Header>();
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
headers.add(new Header("Host", "api.weibo.com"));
headers.add(new Header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"));
HttpClient client = new HttpClient();
client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
client.executeMethod(postMethod);
int status = postMethod.getStatusCode();
if(status != 302){
LOG.error("refresh token failed");
return null;
}
Header location = postMethod.getResponseHeader("Location");
if(location != null){
String retUrl = location.getValue();
int begin = retUrl.indexOf("code=");
if(begin != -1){
int end = retUrl.indexOf("&", begin);
if(end == -1)
end = retUrl.length();
String code = retUrl.substring(begin+5, end);
if(code != null){
AccessToken token = oauth.getAccessTokenByCode(code);
Oauth oauth = new Oauth();
return token;
}
}
}
} catch (FileNotFoundException e) {
LOG.error("error" + e);
} catch (IOException e) {
LOG.error("error" + e);
}
LOG.error("refresh token failed");
return null;
}
现在程序报:200。没法重定向了,如果有哪位大神看到后,知道怎么解决,望赐教!
没有办法,只能获取code,根据code获取access_token了
代码如下:
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="xxxxxx";//你的应用ID
static String clientSecret="xxxxxxxxxxxxxxxxxxxxxxx";//你的应用密码
static String redirectUri="www.baidu.com";//你在应用管理中心设置的回调页面 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()
{
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException
{}
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());
}
}
其实我也挺不喜欢拿来主义的,不过实在没有版办法,在这里要感谢刘哥了,虽然咱们不曾相识,在这里还是要好好感谢!
根据上面的代码获取了access_token,但是token是有生命周期的


工作笔记—新浪微博Oauth2.0授权 获取Access Token (java)的更多相关文章
- 新浪微博Oauth2.0授权 获取Access Token
新浪微博开放平台提供了丰富的API接口,利用这些接口,开发者能够开发出独具特色的微博应用.但是,大部分接口都需要用户授权给应用,应用利用授权得到的Access Token来调用相应的接口来获取内容. ...
- Java微信公众平台开发(十六)--微信网页授权(OAuth2.0授权)获取用户基本信息
转自:http://www.cuiyongzhi.com/post/78.html 好长时间没有写文章了,主要是最近的工作和生活上的事情比较多而且繁琐,其实到现在我依然还是感觉有些迷茫,最后还是决定静 ...
- 新浪微博Oauth2.0授权认证及SDK、API的使用(Android)
---------------------------------------------------------------------------------------------- [版权申明 ...
- iOS实现OAuth2.0中刷新access token并重新请求数据操作
一.简要概述 OAuth2.0是OAuth协议的下一版本,时常用于移动客户端的开发,是一种比较安全的机制.在OAuth 2.0中,server将发行一个短有效期的access token和长生命期的r ...
- oauth2.0授权码模式详解
授权码模式原理 授权码模式(authorization code)是功能最完整.流程最严密的授权模式.它的特点就是通过客户端的后台服务器,与"服务提供商"的认证服务器进行互动. 它 ...
- OAuth2.0授权
一.什么是OAuth2.0官方网站:http://oauth.net/ http://oauth.net/2/ 权威定义:OAuth is An open protocol to allow secu ...
- 微信开发——OAuth2.0授权
微信公众平台最近新推出微信认证,认证后可以获得高级接口权限,其中一个是OAuth2.0网页授权,很多朋友在使用这个的时候失败了或者无法理解其内容,希望我出个教程详细讲解一下,于是便有了这篇文章. 一. ...
- 新浪微博OAuth2.0的用法
最近学习Android开发,照着视频开发新浪微博,但是视频里的介绍的是OAuth1.0的授权方式,试了半天发现用不了. 原来现在一般没审核的用户只能使用OAuth2.0了,视频教学里的方法已经过时了. ...
- Microsoft.Owin.Security.OAuth搭建OAuth2.0授权服务端
Microsoft.Owin.Security.OAuth搭建OAuth2.0授权服务端 目录 前言 OAuth2.0简介 授权模式 (SimpleSSO示例) 使用Microsoft.Owin.Se ...
随机推荐
- PYTHON-函数的定义与调用,返回值,和参数
函数基础'''1. 什么是函数 具备某一功能的工具->函数 事先准备工具的过程--->函数的定义 遇到应用场景,拿来就用---->函数的调用 函数分类两大类: 1. 内置函数 2. ...
- hdu1517 巴什博奕变换
//没必要递推sg,直接巴什博奕即可 /* 先手面对[n/2,n/9]必胜,即后手面对n/18必败 同理,后手面对n/18^2必败... 那么能否使后手面对n/18^k的局势,在于n/18^k是否在[ ...
- hdu3486 ST表区间最值+二分
还是挺简单的,但是区间处理的时候要注意一下 #include<iostream> #include<cstring> #include<cstdio> #inclu ...
- 性能测试十八:jmeter分布式
一台压力机产生得压力是有限的,尤其是jmeter,java本来性能就不是很好,并发特别多的时候,jmeter的性能会急剧下降,正常的接口,若单台压力机,超过1000并发以后,jmeter的性能就不怎么 ...
- plsql developer连接Oracle报错ORA-12154: TNS:could not resolve the connect identifier specified
今日更改Oracle网络配置文件后使用plsql developer 尝试连接到Oracle出现报错 ORA-12154: TNS:could not resolve the connect iden ...
- Django整合Keras报错:ValueError: Tensor Tensor("Placeholder:0", shape=(3, 3, 1, 32), dtype=float32) is not an element of this graph.解决方法
本人在写Django RESful API时,碰到一个难题,老出现,整合Keras,报如下错误:很纠结,探索找资料近一个星期,皇天不负有心人,解决了 Internal Server Error: /p ...
- python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)
昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...
- String中的toCharArray:将此字符串转换为新的字符数组,并统计次数
package stringyiwen; public class StringTestToCharArray { public static void main(String[] args) { S ...
- 【C++ Primer 第13章】3. 交换操作
交换操作 class HasPtr { friend void swap(HasPtr &rhs, HasPtr &yhs); //其他成员定义 }; void swap(HasPtr ...
- hdu 1217 汇率 Floyd
题意:给几个国家,然后给这些国家之间的汇率.判断能否通过这些汇率差进行套利交易. Floyd的算法可以求出任意两点间的最短路径,最后比较本国与本国的汇率差,如果大于1,则可以.否则不可以. 有向图 一 ...