登录页面:
<div class="otherAccount">
<h6>使用其他网站账户登录:</h6>
<ul>
<li>
<a href="${base}/ologin/auth/qq">
<img src="${base}/theme/skin2/images/icon_qq.jpg" />QQ</a>
</li>
<li>
<img src="${base}/theme/skin2/images/dashed.gif" />
</li>
<li>
<a href="${base}/ologin/auth/163">
<img src="${base}/theme/skin2/images/idon_net163.jpg" />网易</a>
</li>
<li>
<img src="${base}/theme/skin2/images/dashed.gif" />
</li>
<li>
<a href="${base}/ologin/auth/renren">
<img src="${base}/theme/skin2/images/icon_renren.jpg" />人人网</a>
</li>
<li>
<img src="${base}/theme/skin2/images/dashed.gif" />
</li>
<li>
<a href="${base}/ologin/auth/sina">
<img src="${base}/theme/skin2/images/icon_sina.jpg" />新浪微博</a>
</li>
<li>
<img src="${base}/theme/skin2/images/dashed.gif" />
</li>
<li>
<a href="${base}/ologin/auth/douban">
<img src="${base}/theme/skin2/images/icon_douBan.jpg" />豆瓣</a>
</li>
</ul>
</div>
对应的controller
package com.chinaj.bpo.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.chinaj.bpo.base.CommonConstant;
import com.chinaj.bpo.base.controller.BaseController;
import com.chinaj.bpo.base.utils.StringUtils;
import com.chinaj.bpo.service.CustomerOperationLogService;
import com.chinaj.bpo.service.OAuthService;
import com.chinaj.bpo.wsclient.vo.TCustomer;
@Controller
@RequestMapping("/ologin")
public class OAuthLoginController extends BaseController {
@Autowired
private OAuthService service;
@Autowired
private CustomerOperationLogService customerOperationLogService;
/**
* 请求开发登录平台未授权的code
* @param origin 用户来源,值为:douban, qq, weibo等
* @return
*/
@RequestMapping("/auth/{origin}")
public String auth(@PathVariable("origin") String origin, Model model) {
String url = service.getAuthUrlByOrigin(origin);
if(StringUtils.isEmpty(url)) return "login/login";
model.addAttribute("url", url);
return "auth";
}
/**
* 授权回调
* @param request
* @return
*/
@RequestMapping("/callback")
public String authCallback(HttpServletRequest request) {
String code = request.getParameter("code");
String error = request.getParameter("error");
String origin = request.getParameter("state");
log.info(code +" "+ error);
if(!StringUtils.isEmpty(error))
return "index";
try {
TCustomer customer = service.token(code, origin);
this.setSessionUser(customer);
customerOperationLogService.saveLog(1, this.getSessionUser().getCustomer(), this.getRequest().getRemoteAddr());
} catch (Exception e) {
log.error("", e);
return "index";
}
String loginToUrl = null;
if( this.getSession().getAttribute(CommonConstant.LOGIN_TO_URL)!=null )
{
loginToUrl = (String) getSession().getAttribute(CommonConstant.LOGIN_TO_URL);
this.getRequest().setAttribute("loginToUrl", loginToUrl);
}
return "index";
}
/**
* 绑定本地帐户
* @return
*/
public String bindLocalAccount() {
return null;
}
/**
* 绑定第三方帐户
* 添加微博地址至联系方式中
* @return
*/
public String bindOAuthAccount() {
return null;
}
/**
* 分享视频、活动、话题等 。。。
* @return
*/
public String share() {
return null;
}
}
对应的service
package com.chinaj.bpo.service;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.chinaj.bpo.base.CommonConstant;
import com.chinaj.bpo.base.SystemBuffer;
import com.chinaj.bpo.base.utils.JsonUtil;
import com.chinaj.bpo.base.utils.OAuthHelper;
import com.chinaj.bpo.base.utils.StringUtils;
import com.chinaj.bpo.wsclient.vo.TCustomer;
import com.chinaj.bpo.wsclient.vo.Token;
import com.chinaj.ecp.market.ws.ICustomer;
import com.chinaj.ecp.market.ws.ILogin;
@Service
public class OAuthService {
protected Log log = LogFactory.getLog(this.getClass());
private ILogin iLogin=SystemBuffer.login;
private ICustomer iCustomer=SystemBuffer.customer;
private Token ecpToken = SystemBuffer.token;
@Autowired
private RegisterService registerService;
/**
* 根据用户来源,组织授权url地址及参数
* @param origin
* @return
*/
public String getAuthUrlByOrigin(String origin) {
StringBuffer url = new StringBuffer();
if(CommonConstant.OAUTH_DOUBAN.equals(origin)) {
url = formateAuthUrl(OAuthHelper.DOUBAN_AUTH_URL, OAuthHelper.DOUBAN_CLIENT_ID, origin);
} else if(CommonConstant.OAUTH_SINA.equals(origin)) {
url = formateAuthUrl(OAuthHelper.SINA_AUTH_URL, OAuthHelper.SINA_CLIENT_ID, origin);
} else if(CommonConstant.OAUTH_QQ.equals(origin)) {
url = formateAuthUrl(OAuthHelper.QQ_AUTH_URL, OAuthHelper.QQ_CLIENT_ID, origin);
} else if(CommonConstant.OAUTH_RENREN.equals(origin)) {
url = formateAuthUrl(OAuthHelper.RENREN_AUTH_URL, OAuthHelper.RENREN_CLIENT_ID, origin);
} else if(CommonConstant.OAUTH_163.equals(origin)) {
url = formateAuthUrl(OAuthHelper.WANGYI_AUTH_URL, OAuthHelper.WANGYI_CLIENT_ID, origin);
}
return url.toString();
}
/**
* 根据code获取token, 并由此得到开放平台的用户信息并持久化
* @param code
* @param origin
* @return TCustomer
* @throws Exception
*/
public TCustomer token(String code, String origin) throws Exception {
String userId = null;
String userName = null;
String clientId=null;
if(CommonConstant.OAUTH_DOUBAN.equals(origin)) {
Map tokenInfo = fetchTokenInfo(OAuthHelper.DOUBAN_TOKEN_URL,
formateTokenParamMap(code, OAuthHelper.DOUBAN_CLIENT_ID, OAuthHelper.DOUBAN_CLIENT_SECRET));
String token = (String) tokenInfo.get("access_token");
userId = (String) tokenInfo.get("douban_user_id");
userName = parseDoubanUserName(fetchUserInfo(OAuthHelper.DOUBAN_USER_INFO_URL, token,null));
} else if(CommonConstant.OAUTH_SINA.equals(origin)) {
Map tokenInfo = fetchTokenInfo(OAuthHelper.SINA_TOKEN_URL,
formateTokenParamMap(code, OAuthHelper.SINA_CLIENT_ID, OAuthHelper.SINA_CLIENT_SECRET));
String token = (String) tokenInfo.get("access_token");
userId = (String) tokenInfo.get("uid");
userName = parseSinaUserName(fetchUserInfo(OAuthHelper.SINA_USER_INFO_URL, token,formateSinaUserParamMap(token,userId)));
} else if(CommonConstant.OAUTH_QQ.equals(origin)) {
Map tokenInfo = fetchQqTokenInfo(OAuthHelper.QQ_TOKEN_URL,
formateTokenParamMap(code, OAuthHelper.QQ_CLIENT_ID, OAuthHelper.QQ_CLIENT_SECRET));
String token = (String) tokenInfo.get("access_token");
userId = parseQqUserName(fetchUserInfo(OAuthHelper.QQ_USER_INFO_URL, token,formateQqUserParamMap(token)));
clientId= parseQqClientId(fetchUserInfo(OAuthHelper.QQ_USER_INFO_URL, token,formateQqUserParamMap(token)));
userName = parseQqnickname(fetchUserInfo(OAuthHelper.QQ_USER_INFO_URL_Z, token,formateQqUserParamMap(token,clientId,userId)));;
} else if(CommonConstant.OAUTH_RENREN.equals(origin)) {
Map tokenInfo = fetchTokenInfo(OAuthHelper.RENREN_TOKEN_URL,
formateTokenParamMap(code, OAuthHelper.RENREN_CLIENT_ID, OAuthHelper.RENREN_CLIENT_SECRET));
String token = (String) tokenInfo.get("access_token");
Map user=JsonUtil.getMap4Json((String) tokenInfo.get("user"));
userId = (String) user.get("id");
userName = (String) user.get("name");
} else if(CommonConstant.OAUTH_163.equals(origin)) {
Map tokenInfo = fetchTokenInfo(OAuthHelper.WANGYI_TOKEN_URL,
formateTokenParamMap(code, OAuthHelper.WANGYI_CLIENT_ID, OAuthHelper.WANGYI_CLIENT_SECRET));
String token = (String) tokenInfo.get("access_token");
userId = (String) tokenInfo.get("uid");
userName = parseWangyiUserName(fetchUserInfo(OAuthHelper.WANGYI_USER_INFO_URL, token,formateQqUserParamMap(token)));
}
log.info("userId: " + userId + " userName: "+userName);
return addOrUpdateUserInfo(userId, userName, origin);
}
/**
* 获取token信息
* @param tokenUrl
* @param paramMap
* @return
*/
private Map fetchTokenInfo(String tokenUrl, Map<String, String[]> paramMap) {
String tokenJsonInfo = OAuthHelper.getAccessToken(tokenUrl, paramMap);
return JsonUtil.getMap4Json(tokenJsonInfo);
}
/**
* 获取token信息
* @param tokenUrl
* @param paramMap
* @return
*/
private Map fetchQqTokenInfo(String tokenUrl, Map<String, String[]> paramMap) {
String tokenJsonInfo = OAuthHelper.getAccessToken(tokenUrl, paramMap);
String t2=null;
Map map=new HashMap();
if(tokenJsonInfo!=null)
{
if(tokenJsonInfo.indexOf("error")==-1){
String t=tokenJsonInfo;
String t1=t.substring(13);
t2=t1.substring(0,t1.indexOf("&"));
map.put("access_token", t2);
getRequest().getSession().setAttribute("qq_access_token", t2);
}else
{
String token=(String) this.getRequest().getSession().getAttribute("qq_access_token");
map.put("access_token", token);
}
}
return map;
}
protected HttpServletRequest getRequest() {
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
/**
* 获取用户信息
* @param tokenUrl
* @param paramMap
* @return
*/
private String fetchUserInfo(String url, String token,Map<String, String[]> paramMap) {
return OAuthHelper.getUserInfo(url, token,paramMap);
}
/**
* 解析douban用户昵称
* @param userXmlInfo
* @return
* @throws DocumentException
*/
private String parseDoubanUserName(String userXmlInfo) throws DocumentException {
Document doc = DocumentHelper.parseText(userXmlInfo);
Element root = doc.getRootElement();
//用户id(不可靠)
Element uid = root.element("uid");
//用户昵称
Element titleElement = root.element("title");
return titleElement.getText();
}
/**
* 解析sina用户昵称
* @param userJsonInfo
* @return
*/
private String parseSinaUserName(String userJsonInfo) {
return (String) JsonUtil.getMap4Json(userJsonInfo).get("name");
}
/**
* 解析qq用户昵称
* @param userJsonInfo
* @return
*/
private String parseQqUserName(String userJsonInfo) {
userJsonInfo=userJsonInfo.substring(9);
userJsonInfo=userJsonInfo.substring(0,userJsonInfo.indexOf(")"));
return (String) JsonUtil.getMap4Json(userJsonInfo).get("openid");
}
private String parseQqClientId(String userJsonInfo) {
userJsonInfo=userJsonInfo.substring(9);
userJsonInfo=userJsonInfo.substring(0,userJsonInfo.indexOf(")"));
return (String) JsonUtil.getMap4Json(userJsonInfo).get("client_id");
}
private String parseQqnickname(String userJsonInfo) {
return (String) JsonUtil.getMap4Json(userJsonInfo).get("nickname");
}
/**
* 解析renren用户昵称
* @param userJsonInfo
* @return
*/
private String parseRenrenUserName(String userJsonInfo) {
return (String) JsonUtil.getMap4Json(userJsonInfo).get("username");
}
/**
* 解析163用户昵称
* @param userJsonInfo
* @return
*/
private String parseWangyiUserName(String userJsonInfo) {
return (String) JsonUtil.getMap4Json(userJsonInfo).get("name");
}
private TCustomer addOrUpdateUserInfo(String oauthUserId, String oauthUserNickName, String origion) {
String localCustomerId = iLogin.checkOAuthAccount(oauthUserId, origion);
TCustomer customer = null;
if(StringUtils.isEmpty(localCustomerId)) {
customer = new TCustomer();
customer.setCustomer(origion+"_"+oauthUserId);
customer.setReservedfield1(oauthUserId);
customer.setReservedfield2(customer.getCustomer());
customer.setReservedfield3(origion);
customer.setReservedfield4(oauthUserNickName);
customer.setSex(2);
int resonCode = registerService.register(customer);
log.info("持久化第三方用户:返code:" + resonCode);
String customerId = iLogin.checkOAuthAccount(oauthUserId, origion);
customer = iCustomer.getCustomer(ecpToken, customerId);
} else {
customer = iCustomer.getCustomer(ecpToken, localCustomerId);
}
return customer;
}
/**
* 组织授权请求的url及传输参数
* @param authUrl
* @param clientId
* @param origin
* @return
*/
private StringBuffer formateAuthUrl(String authUrl, String clientId, String origin) {
return new StringBuffer().append(authUrl)
.append("?client_id=").append(clientId)
.append("&redirect_uri=").append(OAuthHelper.REDIRECT_URL)
.append("&response_type=").append(OAuthHelper.RESPONSE_TYPE)
.append("&state=").append(origin);
}
/**
* 组织请求access token的传输参数
* @param code
* @param clientId
* @param clientSecret
* @return
*/
private Map<String, String[]> formateTokenParamMap(String code, String clientId, String clientSecret) {
Map<String, String[]> paramMap = new HashMap<String, String[]>();
paramMap.put("client_id", new String[]{clientId});
paramMap.put("client_secret", new String[]{clientSecret});
paramMap.put("redirect_uri", new String[]{OAuthHelper.REDIRECT_URL});
paramMap.put("grant_type", new String[]{OAuthHelper.GRANT_TYPE});
paramMap.put("code", new String[]{code});
return paramMap;
}
/**
* 组织请求Sina取 用户的传输参数
* @param code
* @param clientId
* @param clientSecret
* @return
*/
private Map<String, String[]> formateSinaUserParamMap(String token, String uid) {
Map<String, String[]> paramMap = new HashMap<String, String[]>();
paramMap.put("source", new String[]{OAuthHelper.SINA_CLIENT_ID});
paramMap.put("access_token", new String[]{token});
paramMap.put("uid", new String[]{uid});
return paramMap;
}
/**
* 组织请求QQ取 用户的传输参数
* @param code
* @param clientId
* @param clientSecret
* @return
*/
private Map<String, String[]> formateQqUserParamMap(String token) {
Map<String, String[]> paramMap = new HashMap<String, String[]>();
paramMap.put("access_token", new String[]{token});
return paramMap;
}
/**
* 组织请求QQ取 用户的传输参数
* @param code
* @param clientId
* @param clientSecret
* @return
*/
private Map<String, String[]> formateQqUserParamMap(String token,String oauth_consumer_key,String openid) {
Map<String, String[]> paramMap = new HashMap<String, String[]>();
paramMap.put("access_token", new String[]{token});
paramMap.put("oauth_consumer_key", new String[]{oauth_consumer_key});
paramMap.put("openid", new String[]{openid});
return paramMap;
}
public static void main(String[] args) {
// String userInfo = OAuthHelper.getUserInfo(OAuthHelper.SINA_USER_INFO_URL, "2.00i7MOiBRqE1OD870c96d3150lucWT");
// System.out.println(userInfo);
// String t="access_token=793B6554831EEC46BA9377645ACA695E&expires_in=7776000";
// String t1=t.substring(13);
// String t2=t1.substring(0,t1.indexOf("&"));
// System.out.println(t2);
}
}
创建一个第三方帐号辅助工具
package com.wwwcoffee.utils;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class OAuthHelper {
private static Log log = LogFactory.getLog(OAuthHelper.class);
public static String RESPONSE_TYPE;
public static String GRANT_TYPE;
public static String REDIRECT_URL;
public static String DOUBAN_AUTH_URL;
public static String DOUBAN_TOKEN_URL;
public static String DOUBAN_CLIENT_ID;
public static String DOUBAN_CLIENT_SECRET;
public static String DOUBAN_USER_INFO_URL;
public static String SINA_AUTH_URL;
public static String SINA_TOKEN_URL;
public static String SINA_CLIENT_ID;
public static String SINA_CLIENT_SECRET;
public static String SINA_USER_INFO_URL;
public static String QQ_AUTH_URL;
public static String QQ_TOKEN_URL;
public static String QQ_CLIENT_ID;
public static String QQ_CLIENT_SECRET;
public static String QQ_USER_INFO_URL;
public static String QQ_USER_INFO_URL_Z;
public static String RENREN_AUTH_URL;
public static String RENREN_TOKEN_URL;
public static String RENREN_CLIENT_ID;
public static String RENREN_CLIENT_SECRET;
public static String RENREN_USER_INFO_URL;
public static String WANGYI_AUTH_URL;
public static String WANGYI_TOKEN_URL;
public static String WANGYI_CLIENT_ID;
public static String WANGYI_CLIENT_SECRET;
public static String WANGYI_USER_INFO_URL;
static {
InputStream is = ErrorHelper.class.getResourceAsStream("/oauth.properties");
try {
Properties props = new Properties();
props.load(is);
RESPONSE_TYPE = props.getProperty("response_type");
GRANT_TYPE = props.getProperty("grant_type");
REDIRECT_URL = props.getProperty("redirect_uri");
DOUBAN_AUTH_URL = props.getProperty("douban_auth_url");
DOUBAN_TOKEN_URL = props.getProperty("douban_token_url");
DOUBAN_CLIENT_ID = props.getProperty("douban_client_id");
DOUBAN_CLIENT_SECRET = props.getProperty("douban_client_secret");
DOUBAN_USER_INFO_URL = props.getProperty("douban_user_info_url");
SINA_AUTH_URL = props.getProperty("sina_auth_url");
SINA_TOKEN_URL = props.getProperty("sina_token_url");
SINA_CLIENT_ID = props.getProperty("sina_client_id");
SINA_CLIENT_SECRET = props.getProperty("sina_client_secret");
SINA_USER_INFO_URL = props.getProperty("sina_user_info_url");
QQ_AUTH_URL = props.getProperty("qq_auth_url");
QQ_TOKEN_URL = props.getProperty("qq_token_url");
QQ_CLIENT_ID = props.getProperty("qq_client_id");
QQ_CLIENT_SECRET = props.getProperty("qq_client_secret");
QQ_USER_INFO_URL = props.getProperty("qq_user_info_url");
QQ_USER_INFO_URL_Z=props.getProperty("qq_user_info_url_Z");
RENREN_AUTH_URL = props.getProperty("renren_auth_url");
RENREN_TOKEN_URL = props.getProperty("renren_token_url");
RENREN_CLIENT_ID = props.getProperty("renren_client_id");
RENREN_CLIENT_SECRET = props.getProperty("renren_client_secret");
RENREN_USER_INFO_URL = props.getProperty("renren_user_info_url");
WANGYI_AUTH_URL = props.getProperty("163_auth_url");
WANGYI_TOKEN_URL = props.getProperty("163_token_url");
WANGYI_CLIENT_ID = props.getProperty("163_client_id");
WANGYI_CLIENT_SECRET = props.getProperty("163_client_secret");
WANGYI_USER_INFO_URL = props.getProperty("163_user_info_url");
} catch(Exception e) {
}
}
/**
* 获取未授权的code
* @param url 调用url
* @return
*/
public static String auth(String url) {
if (url.endsWith("/"))
url = url.substring(0, url.length() - 1);
URLConnection urlConnection = null;
BufferedReader br = null;
try {
// 组装调用URL
// 执行调用
urlConnection = new URL(url).openConnection();
log.info("Invoke HTTP interface: " + url);
urlConnection.setConnectTimeout(10 * 1000);
br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
log.error("Failed to invoke HTTP interface: " + url, e);
return null;
} finally {
urlConnection = null;
try {
br.close();
} catch (Exception e1) {
}
br = null;
}
}
/**
* 获取access token
* @param url
* @param paramMap
* @return
*/
public static String getAccessToken(String url,
Map<String, String[]> paramMap) {
if (url.endsWith("/"))
url = url.substring(0, url.length() - 1);
TrustManager[] tm = null;
SSLContext sslContext = null;
SSLSocketFactory ssf = null;
HttpsURLConnection httpsConn = null;
BufferedReader br = null;
BufferedOutputStream bos = null;
try {
tm = new TrustManager[]{ new MyX509TrustManager() };
sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
ssf = sslContext.getSocketFactory();
// 执行调用
httpsConn = (HttpsURLConnection) new URL(url).openConnection();
httpsConn.setSSLSocketFactory(ssf);
httpsConn.setDoInput(true);
httpsConn.setDoOutput(true);
httpsConn.setUseCaches(false);
bos = new BufferedOutputStream(httpsConn.getOutputStream());
// 组装调用参数
int count = 0;
Iterator<String> paramNameIter = paramMap.keySet().iterator();
String paramName = null;
String[] paramValues = null;
while (paramNameIter.hasNext()) {
paramName = paramNameIter.next();
paramValues = paramMap.get(paramName);
if (count > 0)
bos.write("&".getBytes());
bos.write((paramName + "=").getBytes());
if (paramValues != null && paramValues.length > 0) {
for (int i = 0; i < paramValues.length; i++) {
if (i > 0)
bos.write(",".getBytes());
bos.write(paramValues[i].getBytes());
}
}
count++;
}
log.info("Invoke HTTP interface: " + url);
httpsConn.setConnectTimeout(10 * 1000);
bos.flush();
InputStreamReader read = new InputStreamReader(httpsConn.getInputStream(), "utf-8");
br = new BufferedReader(read);
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
log.error("Failed to invoke HTTP interface: " + url, e);
return null;
} finally {
tm = null;
sslContext = null;
ssf = null;
httpsConn = null;
try {
br.close();
bos.close();
} catch (Exception e1) {
}
br = null;
bos = null;
}
}
/**
* 通过获取的access token,取得开放平台中用户的信息
* @param url 调用url
* @param accessToken
* @return
*/
public static String getUserInfo(String url, String accessToken,Map<String, String[]> paramMap) {
if (url.endsWith("/"))
url = url.substring(0, url.length() - 1);
TrustManager[] tm = null;
SSLContext sslContext = null;
SSLSocketFactory ssf = null;
HttpsURLConnection httpsConn = null;
BufferedReader br = null;
String uri="";
try {
tm = new TrustManager[]{ new MyX509TrustManager() };
sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
ssf = sslContext.getSocketFactory();
// 组装调用URL
// 执行调用
if(paramMap!=null)
{
// 组装调用参数
int count = 0;
Iterator<String> paramNameIter = paramMap.keySet().iterator();
String paramName = null;
String[] paramValues = null;
while (paramNameIter.hasNext()) {
paramName = paramNameIter.next();
paramValues = paramMap.get(paramName);
if (count > 0)
uri+="&";
uri+=paramName + "=";
if (paramValues != null && paramValues.length > 0) {
for (int i = 0; i < paramValues.length; i++) {
if (i > 0)uri+=",";
uri+=paramValues[i];
}
}
count++;
}
httpsConn = (HttpsURLConnection) new URL(url+"?"+uri).openConnection();
httpsConn.setSSLSocketFactory(ssf);
}else
{
httpsConn = (HttpsURLConnection) new URL(url).openConnection();
httpsConn.setSSLSocketFactory(ssf);
log.info("Invoke HTTP interface: " + url);
httpsConn.setConnectTimeout(10 * 1000);
httpsConn.addRequestProperty("Authorization", "Bearer " + accessToken);
}
InputStreamReader read = new InputStreamReader(httpsConn.getInputStream(), "utf-8");
br = new BufferedReader(read);
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
log.error("Failed to invoke HTTP interface: " + url, e);
return null;
} finally {
tm = null;
sslContext = null;
ssf = null;
httpsConn = null;
try {
br.close();
} catch (Exception e1) {
}
br = null;
}
}
}
创建一个第三方帐号的相关配置文档oauth.properties
response_type=code
grant_type=authorization_code
redirect_uri=http://z.chinaj.com/ologin/callback
douban_auth_url=https://www.douban.com/service/auth2/auth
douban_client_id=0a21d277d03338f61e6577677099aae2
douban_client_secret=601d7aca56c2795a
douban_token_url=https://www.douban.com/service/auth2/token
douban_user_info_url=https://api.douban.com/people/@me
sina_auth_url=https://api.weibo.com/oauth2/authorize
sina_client_id=1195474417
sina_client_secret=762e1845124c2ae824a6e91f9435d26b
sina_token_url=https://api.weibo.com/oauth2/access_token
sina_user_info_url=https://api.weibo.com/2/users/show.json
qq_auth_url=https://graph.qq.com/oauth2.0/authorize
qq_client_id=100312572
qq_client_secret=5665a46f2be1e63040fd75857961ae12
qq_token_url=https://graph.qq.com/oauth2.0/token
qq_user_info_url=https://graph.qq.com/oauth2.0/me
qq_user_info_url_Z=https://graph.qq.com/user/get_user_info
renren_auth_url=https://graph.renren.com/oauth/authorize
renren_client_id=e10fb769f6204e19a6cc8a146ad30636
renren_client_secret=08cf922621964e14a3ed1c2c1aa6ee51
renren_token_url=https://graph.renren.com/oauth/token
renren_user_info_url=https://graph.renren.com/oauth/token
163_auth_url=https://api.t.163.com/oauth2/authorize
163_client_id=jlluVFX69TACv1IH
163_client_secret=SVqqWLEa1p2cRyiRc2cHJmtyz8h5vAWr
163_token_url=https://api.t.163.com/oauth2/access_token
163_user_info_url=https://api.t.163.com/users/show.json