很少接触网络编程,为了微博的自动授权,学习了一下。现完成代码如下。
分为三部分:java 代码,配置文件,qq密码加密js
JAVA代码
import net.javawind.tencent.entity.App;
import net.javawind.tencent.entity.Token;
import net.javawind.tencent.util.OAuthClient;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weibo4j.Oauth;
import weibo4j.http.AccessToken;
import weibo4j.model.WeiboException;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
/**
* 文件描述: 自动获取微博的授权码
* 内容摘要: 用于微博的自动授权,自动获取code
* 其他说明: // 其它内容的说明
* 版本 1.0
* 完成日期:13-1-8下午1:56
*
* 修改日期:13-1-8下午1:56
* 版 本 号:1.0
* 修改内容://修改内容描述
*
*/
public class RefreshAccessToken {
private static Log log = LogFactory.getLog(RefreshAccessToken.class);
private static AccessToken refreshSinaToken() {
Properties props = new Properties();
try {
props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
String url = props.getProperty("authorizeURL");/*模拟登录的地址,https://api.weibo.com/oauth2/authorize*/
PostMethod postMethod = new PostMethod(url);
postMethod.addParameter("client_id", props.getProperty("client_ID"));//你的 client id
postMethod.addParameter("redirect_uri", props.getProperty("redirect_URI"));//你的回调 url
postMethod.addParameter("userId", props.getProperty("userId"));//微博的帐号
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 headers = new ArrayList();
headers.add(new Header("Referer", props.getProperty("authorizeURL")+"?client_id=" + props.getProperty("client_ID") + "&redirect_uri=" + props.getProperty("redirect_URI") + "&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("Weibo 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) {
Oauth oauth = new Oauth();
AccessToken token = oauth.getAccessTokenByCode(code);
return token;
}
}
}
} catch (WeiboException we) {
log.error("---Weibo Error---", we);
} catch (FileNotFoundException e) {
log.error("---Weibo Error FileNotFoundException---", e);
} catch (IOException e) {
log.error("---Weibo Error IOException---", e);
}
return null;
}
/**
* 对登录密码进行加密
*
* @param password
* @param verifyCode
* @param verifyCodeHex
* @return
*/
private static String encodePass(String password, String verifyCode, String verifyCodeHex) {
try {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("encodePass.js");
Reader inreader = new InputStreamReader(in);
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine se = m.getEngineByName("javascript");
se.eval(inreader);
Object t = se.eval("passwordEncoding(\"" + password + "\",\"" + verifyCodeHex
+ "\",\"" + verifyCode.toUpperCase() + "\");");
return t.toString();
} catch (Exception e) {
log.error("-QQ--Weibo encodePass Exception---", e);
}
return null;
}
/**
* 得到请求返回的响应的内容
*
* @param getMethod
* @return
*/
private static String getResponseString(GetMethod getMethod) {
try {
if (getMethod.getResponseHeader("Content-Encoding") != null && getMethod.getResponseHeader("Content-Encoding").getValue().equals("gzip")) {
BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(getMethod.getResponseBodyAsStream()), "UTF-8"));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} else {
return getMethod.getResponseBodyAsString();
}
} catch (IOException e) {
log.error("-QQ--Weibo getResponseString Exception---", e);
}
return null;
}
/**
* 获取QQ的授权token
*
* @return
*/
public static Token refreshQQToken() {
Properties props = new Properties();
try {
props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
App app = new App();
OAuthClient auth = new OAuthClient();
String qq = props.getProperty("qq");
String password = props.getProperty("qqPassword");
String verifycode = "";
String referer = auth.authorize(app);
String checkUrl = props.getProperty("qcheckURL")+"?uin=" + qq + "&appid=46000101&r=" + Math.random();
List header1 = new ArrayList();
header1.add(new Header("Referer", referer));//伪造referer
header1.add(new Header("Accept", "*/*"));
header1.add(new Header("Connection", "keep-alive"));
header1.add(new Header("Accept-Encoding", "gzip, deflate"));
header1.add(new Header("Accept-Language", "zh-cn"));
header1.add(new Header("Host", "ssl.ptlogin2.qq.com"));
header1.add(new Header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0"));
//第一次请求,为了得到sessionKey
HttpClient client = new HttpClient();
client.getHostConfiguration().getParams().setParameter("http.default-headers", header1);
GetMethod getMethod = new GetMethod(referer);
getMethod.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
client.executeMethod(getMethod);
String response = getResponseString(getMethod);
String cookie = "";
int x = response.indexOf("sessionKey=");
String sessionKey = response.substring(x + 11, x + 43);
getMethod.releaseConnection();
log.info("first request---cookie:" + cookie + "---sessionKey---" + sessionKey);
//第二次请求,验证是否需要填写验证码,并得到相应的cookie
client.getHostConfiguration().getParams().setParameter("http.default-headers", header1);
getMethod = new GetMethod(checkUrl);
getMethod.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
client.executeMethod(getMethod);
Header header = getMethod.getResponseHeader("Set-Cookie");
cookie = header.getValue() + cookie;
response = getResponseString(getMethod);
log.info("second request---cookie:" + cookie + "---response---" + response);
// String faceback="ptui_checkVC('0','!SSP','\\x00\\x00\\x00\\x00\\x9d\\x58\\x05\\xb4');";
String checkAccountVCRegex = "\\'(.+)\\'\\,\\'(.+)\\'\\,\\'(.+)\\'";
Pattern p = Pattern.compile(checkAccountVCRegex);
Matcher m = p.matcher(response);
String checkType = "";
String verifycodeHex = "";
if (m.find()) {
checkType = m.group(1);
verifycode = m.group(2);
verifycodeHex = m.group(3);
}
if (!checkType.equals("0")) {
//需要填写验证码
log.error("refresh token failed! qq need verifycode!");
return null;
}
getMethod.releaseConnection();
//第三次请求,进行登录认证
String encodePass = encodePass(password, verifycode, verifycodeHex);
String tm= URLEncoder.encode(props.getProperty("qredirect_URI"), "UTF-8");
String url=props.getProperty("qauthorizeURL")+"?client_id="+props.getProperty("qclient_ID")+"&response_type="+props.getProperty("qresponse_type_code")+"&redirect_uri="+tm;
url=URLEncoder.encode(url,"utf-8");
String loginUrl = props.getProperty("qloginURL")+"?ptlang=2052&u=" + qq + "&p=" + encodePass + "&verifycode=" + verifycode + "&aid=46000101&target=top&u1="+url+"%26checkStatus%3Dyes%26appfrom%3D%26g_tk%3D%26sessionKey%3D" + sessionKey + "%26checkType%3DshowAuth%26state%3D&ptredirect=1&h=1&from_ui=1&dumy=&qlogin_param=abbfew=ddd&wording=%E6%8E%88%E6%9D%83&fp=loginerroralert&action=5-10-199999&g=1&t=1&dummy=&js_type=2&js_ver=10009";
header1.add(new Header("Cookie", cookie));
getMethod = new GetMethod(loginUrl);
getMethod.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
client.executeMethod(getMethod);
header = getMethod.getResponseHeader("Set-Cookie");
if (header != null) {
cookie = header.getValue() + cookie;
}
response = getResponseString(getMethod);
log.info("third request---cookie:" + cookie + "---response---" + response);
p = Pattern.compile("登录成功");
m = p.matcher(response);
String getCodeUrl = "";
if (m.find()) {
//登录成功
x = response.indexOf("https");
String sub = response.substring(x, response.length());
x = sub.indexOf(",");
getCodeUrl = sub.substring(0, x - 1);
} else {
log.error("refresh token failed! qq login failed");
return null;
}
getMethod.releaseConnection();
//第四次请求,得到code
log.info("fourth request---getCodeUrl---" + getCodeUrl);
x = cookie.indexOf("skey");
String subCookie = cookie.substring(x, cookie.length());
x = subCookie.indexOf(";");
int y = subCookie.indexOf("=");
String tmp = subCookie.substring(y + 1, x);
x=cookie.indexOf("RK=");
subCookie=cookie.substring(x,cookie.length());
x=subCookie.indexOf(";");
y=subCookie.indexOf("=");
String tmpRK=subCookie.substring(y+1,x);
cookie = "ptisp=cnc; pt2gguin=o"+qq+"; uin=o"+qq+"; skey=" + tmp + "; RK="+tmpRK+"; ptui_loginuin="+qq;
header1.add(new Header("Cookie", cookie));
header1.add(new Header("Host", "open.t.qq.com"));
client.getHostConfiguration().getParams().setParameter("http.default-headers", header1);
getMethod = new GetMethod(getCodeUrl);
getMethod.setFollowRedirects(true);
client.executeMethod(getMethod);
response = getResponseString(getMethod);
getMethod.releaseConnection();
//
log.info("fourth request---response---" + response);
//取code
x = response.indexOf("code=");
String sub = response.substring(x + 5, response.length());
x = sub.indexOf("&");
String code = sub.substring(0, x);
//取openid
x = response.indexOf("openid=");
sub = response.substring(x + 5, response.length());
x = sub.indexOf("&");
String openid = sub.substring(0, x);
//取openkey
x = response.indexOf("openkey=");
sub = response.substring(x + 5, response.length());
x = sub.indexOf("&");
String openkey = sub.substring(0, x);
log.info("fourth request---code---" + code + "---openid---" + openid + "---openkey----" + openkey);
Token token = auth.token(app, code);
new QqWeibo().setToken(token.getAccess_token());
token.setOpenid(openid);
token.setOpenkey(openkey);
return token;
} catch (Exception e) {
log.error("-QQ--Weibo refreshToken Exception---", e);
}
log.error("refresh token failed");
return null;
}
}
配置文件内容
//新浪部分
client_ID =
client_SERCRET =
redirect_URI =http://192.168.1.100/baidu/accessToken.do?weiboFlag=s
baseURL=https://api.weibo.com/2/
accessTokenURL=https://api.weibo.com/oauth2/access_token
authorizeURL=https://api.weibo.com/oauth2/authorize
//QQ部分
qclient_ID =
qclient_SERCRET =
qresponse_type_code=code
qgrant_type_authorization_code = authorization_code
qgrant_type_refresh_token = refresh_token
qredirect_URI =http://192.168.1.100/baidu/accessToken.do?weiboFlag=q
qbaseURL= https://open.t.qq.com/api/
qaccessTokenURL=https://open.t.qq.com/cgi-bin/oauth2/access_token
qauthorizeURL=https://open.t.qq.com/cgi-bin/oauth2/authorize
qrefreshTokenURL=http://192.168.1.100/baidu/refreshToken.do?weiboFlag=q
qcheckURL=https://ssl.ptlogin2.qq.com/check
qloginURL=https://ssl.ptlogin2.qq.com/login
qq=
qqPassword=
js部分
var hexcase = 1;
var b64pad = "";
var chrsz = 8;
var mode = 32;
function md5(A) {
return hex_md5(A)
}
function hex_md5(A) {
return binl2hex(core_md5(str2binl(A), A.length * chrsz))
}
function str_md5(A) {
return binl2str(core_md5(str2binl(A), A.length * chrsz))
}
function hex_hmac_md5(A, B) {
return binl2hex(core_hmac_md5(A, B))
}
function b64_hmac_md5(A, B) {
return binl2b64(core_hmac_md5(A, B))
}
function str_hmac_md5(A, B) {
return binl2str(core_hmac_md5(A, B))
}
function core_md5(K, F) {
K[F >> 5] |= 128 << ((F) % 32);
K[(((F + 64) >>> 9) << 4) + 14] = F;
var J = 1732584193;
var I = -271733879;
var H = -1732584194;
var G = 271733878;
for ( var C = 0; C < K.length; C += 16) {
var E = J;
var D = I;
var B = H;
var A = G;
J = md5_ff(J, I, H, G, K[C + 0], 7, -680876936);
G = md5_ff(G, J, I, H, K[C + 1], 12, -389564586);
H = md5_ff(H, G, J, I, K[C + 2], 17, 606105819);
I = md5_ff(I, H, G, J, K[C + 3], 22, -1044525330);
J = md5_ff(J, I, H, G, K[C + 4], 7, -176418897);
G = md5_ff(G, J, I, H, K[C + 5], 12, 1200080426);
H = md5_ff(H, G, J, I, K[C + 6], 17, -1473231341);
I = md5_ff(I, H, G, J, K[C + 7], 22, -45705983);
J = md5_ff(J, I, H, G, K[C + 8], 7, 1770035416);
G = md5_ff(G, J, I, H, K[C + 9], 12, -1958414417);
H = md5_ff(H, G, J, I, K[C + 10], 17, -42063);
I = md5_ff(I, H, G, J, K[C + 11], 22, -1990404162);
J = md5_ff(J, I, H, G, K[C + 12], 7, 1804603682);
G = md5_ff(G, J, I, H, K[C + 13], 12, -40341101);
H = md5_ff(H, G, J, I, K[C + 14], 17, -1502002290);
I = md5_ff(I, H, G, J, K[C + 15], 22, 1236535329);
J = md5_gg(J, I, H, G, K[C + 1], 5, -165796510);
G = md5_gg(G, J, I, H, K[C + 6], 9, -1069501632);
H = md5_gg(H, G, J, I, K[C + 11], 14, 643717713);
I = md5_gg(I, H, G, J, K[C + 0], 20, -373897302);
J = md5_gg(J, I, H, G, K[C + 5], 5, -701558691);
G = md5_gg(G, J, I, H, K[C + 10], 9, 38016083);
H = md5_gg(H, G, J, I, K[C + 15], 14, -660478335);
I = md5_gg(I, H, G, J, K[C + 4], 20, -405537848);
J = md5_gg(J, I, H, G, K[C + 9], 5, 568446438);
G = md5_gg(G, J, I, H, K[C + 14], 9, -1019803690);
H = md5_gg(H, G, J, I, K[C + 3], 14, -187363961);
I = md5_gg(I, H, G, J, K[C + 8], 20, 1163531501);
J = md5_gg(J, I, H, G, K[C + 13], 5, -1444681467);
G = md5_gg(G, J, I, H, K[C + 2], 9, -51403784);
H = md5_gg(H, G, J, I, K[C + 7], 14, 1735328473);
I = md5_gg(I, H, G, J, K[C + 12], 20, -1926607734);
J = md5_hh(J, I, H, G, K[C + 5], 4, -378558);
G = md5_hh(G, J, I, H, K[C + 8], 11, -2022574463);
H = md5_hh(H, G, J, I, K[C + 11], 16, 1839030562);
I = md5_hh(I, H, G, J, K[C + 14], 23, -35309556);
J = md5_hh(J, I, H, G, K[C + 1], 4, -1530992060);
G = md5_hh(G, J, I, H, K[C + 4], 11, 1272893353);
H = md5_hh(H, G, J, I, K[C + 7], 16, -155497632);
I = md5_hh(I, H, G, J, K[C + 10], 23, -1094730640);
J = md5_hh(J, I, H, G, K[C + 13], 4, 681279174);
G = md5_hh(G, J, I, H, K[C + 0], 11, -358537222);
H = md5_hh(H, G, J, I, K[C + 3], 16, -722521979);
I = md5_hh(I, H, G, J, K[C + 6], 23, 76029189);
J = md5_hh(J, I, H, G, K[C + 9], 4, -640364487);
G = md5_hh(G, J, I, H, K[C + 12], 11, -421815835);
H = md5_hh(H, G, J, I, K[C + 15], 16, 530742520);
I = md5_hh(I, H, G, J, K[C + 2], 23, -995338651);
J = md5_ii(J, I, H, G, K[C + 0], 6, -198630844);
G = md5_ii(G, J, I, H, K[C + 7], 10, 1126891415);
H = md5_ii(H, G, J, I, K[C + 14], 15, -1416354905);
I = md5_ii(I, H, G, J, K[C + 5], 21, -57434055);
J = md5_ii(J, I, H, G, K[C + 12], 6, 1700485571);
G = md5_ii(G, J, I, H, K[C + 3], 10, -1894986606);
H = md5_ii(H, G, J, I, K[C + 10], 15, -1051523);
I = md5_ii(I, H, G, J, K[C + 1], 21, -2054922799);
J = md5_ii(J, I, H, G, K[C + 8], 6, 1873313359);
G = md5_ii(G, J, I, H, K[C + 15], 10, -30611744);
H = md5_ii(H, G, J, I, K[C + 6], 15, -1560198380);
I = md5_ii(I, H, G, J, K[C + 13], 21, 1309151649);
J = md5_ii(J, I, H, G, K[C + 4], 6, -145523070);
G = md5_ii(G, J, I, H, K[C + 11], 10, -1120210379);
H = md5_ii(H, G, J, I, K[C + 2], 15, 718787259);
I = md5_ii(I, H, G, J, K[C + 9], 21, -343485551);
J = safe_add(J, E);
I = safe_add(I, D);
H = safe_add(H, B);
G = safe_add(G, A)
}
if (mode == 16) {
return Array(I, H)
} else {
return Array(J, I, H, G)
}
}
function md5_cmn(F, C, B, A, E, D) {
return safe_add(bit_rol(safe_add(safe_add(C, F), safe_add(A, D)), E), B)
}
function md5_ff(C, B, G, F, A, E, D) {
return md5_cmn((B & G) | ((~B) & F), C, B, A, E, D)
}
function md5_gg(C, B, G, F, A, E, D) {
return md5_cmn((B & F) | (G & (~F)), C, B, A, E, D)
}
function md5_hh(C, B, G, F, A, E, D) {
return md5_cmn(B ^ G ^ F, C, B, A, E, D)
}
function md5_ii(C, B, G, F, A, E, D) {
return md5_cmn(G ^ (B | (~F)), C, B, A, E, D)
}
function core_hmac_md5(C, F) {
var E = str2binl(C);
if (E.length > 16) {
E = core_md5(E, C.length * chrsz)
}
var A = Array(16), D = Array(16);
for ( var B = 0; B < 16; B++) {
A[B] = E[B] ^ 909522486;
D[B] = E[B] ^ 1549556828
}
var G = core_md5(A.concat(str2binl(F)), 512 + F.length * chrsz);
return core_md5(D.concat(G), 512 + 128)
}
function safe_add(A, D) {
var C = (A & 65535) + (D & 65535);
var B = (A >> 16) + (D >> 16) + (C >> 16);
return (B << 16) | (C & 65535)
}
function bit_rol(A, B) {
return (A << B) | (A >>> (32 - B))
}
function str2binl(D) {
var C = Array();
var A = (1 << chrsz) - 1;
for ( var B = 0; B < D.length * chrsz; B += chrsz) {
C[B >> 5] |= (D.charCodeAt(B / chrsz) & A) << (B % 32)
}
return C
}
function binl2str(C) {
var D = "";
var A = (1 << chrsz) - 1;
for ( var B = 0; B < C.length * 32; B += chrsz) {
D += String.fromCharCode((C[B >> 5] >>> (B % 32)) & A)
}
return D
}
function binl2hex(C) {
var B = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var D = "";
for ( var A = 0; A < C.length * 4; A++) {
D += B.charAt((C[A >> 2] >> ((A % 4) * 8 + 4)) & 15)
+ B.charAt((C[A >> 2] >> ((A % 4) * 8)) & 15)
}
return D
}
function binl2b64(D) {
var C = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var F = "";
for ( var B = 0; B < D.length * 4; B += 3) {
var E = (((D[B >> 2] >> 8 * (B % 4)) & 255) << 16)
| (((D[B + 1 >> 2] >> 8 * ((B + 1) % 4)) & 255) << 8)
| ((D[B + 2 >> 2] >> 8 * ((B + 2) % 4)) & 255);
for ( var A = 0; A < 4; A++) {
if (B * 8 + A * 6 > D.length * 32) {
F += b64pad
} else {
F += C.charAt((E >> 6 * (3 - A)) & 63)
}
}
}
return F
}
function hexchar2bin(str) {
var arr = [];
for ( var i = 0; i < str.length; i = i + 2) {
arr.push("\\x" + str.substr(i, 2))
}
arr = arr.join("");
eval("var temp = '" + arr + "'");
return temp
}
function uin2hex(str) {
var maxLength = 16;
str = parseInt(str);
var hex = str.toString(16);
var len = hex.length;
for ( var i = len; i < maxLength; i++) {
hex = "0" + hex
}
var arr = [];
for ( var j = 0; j < maxLength; j += 2) {
arr.push("\\x" + hex.substr(j, 2))
}
var result = arr.join("");
eval('result="' + result + '"');
return result
}
//加密
function passwordEncoding(password, code2, verifycode) {
var I = hexchar2bin(md5(password));
var H = md5(I + code2);
var G = md5(H + verifycode);
return G;
}