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

时间:2022-01-12 05:46:14

  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 (java)