工作笔记—新浪微博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 ...
随机推荐
- 019_nginx upstream中keepalive参数
一. TCP/IP State=>SYN_RECV,LISTEN,TIME_WAIT,ESTABLISHED,STREAM,CONNECTED,CLOSING (1)前端Nginx大量报no l ...
- shell脚本中冒号
格式:: your comment here 格式:# your comment here 写代码注释(单行注释). 例如: 格式:: 'comment line1 comment line2 mor ...
- 前端实现商品sku属性选择
一.效果图 二.后台返回的数据格式 [{ "saleName": "颜色", "dim": 1, "saleAttrList&qu ...
- 【必备】史上最全的浏览器 CSS & JS Hack 手册
[必备]史上最全的浏览器 CSS & JS Hack 手册 浏览器渲染页面的方式各不相同,甚至同一浏览器的不同版本(“杰出代表”是 IE)也有差异.因此,浏览器兼容成为前端开发人员的必备技 ...
- Linux mount 修改文件系统的读写属性
有时候要在某个文件夹下添加和删除文件时,显示 "read only filesystem",说明该文件系统是只读的不能修改.使用 mount –o remount,rw / 命令可 ...
- LeetCode(44): 通配符匹配
Hard! 题目描述: 给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配. '?' 可以匹配任何单个字符. '*' 可以匹配任意字符串(包括空字符串). ...
- TLiteSQLMonitor 使用方法
- django----文件配置
静态路径配置 STATIC_URL = '/static/' #这个配置就相当于下面配置的别名,如果这里的名字修改了就按照这里的名字去导入 STATICFILES_DIRS = [ os.path.j ...
- windows 系统常用操作
1.所有端口使用情况 netstat -ano 2.查询xxxx端口pid netstat -aon|findstr "xxxx" 3.根据端口Pid查详情 tasklist|fi ...
- 2017-2018-2 20155309南皓芯 Exp6 信息搜集与漏洞扫描
实践内容 1.各种搜索技巧的应用 2.DNS IP注册信息的查询 3.基本的扫描技术:主机发现.端口扫描.OS及服务版本探测.具体服务的查点 4.漏洞扫描:会扫,会看报告,会查漏洞说明,会修补漏洞 基 ...