JAVA實現第三方網站QQ掃碼登入Demo
由於公司要用JAVA實現QQ掃碼登入的需求,經過3天的奮戰終於實現了這個功能,這個是用Servlet實現的Demo,很容易遷移進專案,不說多了,下面貼下程式碼
ConstantManager.java
package com.qq.common;
import java.net.URLEncoder;
public class ConstantManager {
//使用者詳細資訊 public static final String OAUTH_USER_INFO="snsapi_userinfo"; public static final String OAUTH_QQ_USER_INFO="get_user_info"; //靜默授權 public static final String OAUTH_USER_BASE="snsapi_base"; public static final String GRANT_TYPE="authorization_code"; //網頁授權作用域 public static final String OAUTH_WEB_LOGIN="snsapi_login"; public static final String PC="pc"; public static final String WAP="wap"; /** * QQ登入回撥 */ public static final String QQCALLBACKURL = URLEncoder.encode("http://www.sucaiku.xin/callback/getQqCallback");
}
UrlConfig.java
package com.qq.common;
import org.apache.commons.lang3.StringUtils;
/**
*
- @description 微信介面呼叫地址配置
- @author tjz
- @time 2017年2月23日
*/
public class UrlConfig {
/** * 微信全域性呼叫accessToken * * @return */ public String getGlobalAccessTokenUrl(String wxMpAppId,String wxMpAppSecrte) { return "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + wxMpAppId + "&secret="+ wxMpAppSecrte; } /** * 微信伺服器IP列表 * * @return */ public String getWeiXinIpUrl(String wxMpAppId,String wxMpAppSecrte,String appId) { //return "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" + weiXinUtil.getGlobalAccessToken(wxMpAppId, wxMpAppSecrte,appId); return null; } /** * 微信授權 */ public String getOauth(String type,String redirectUrl,String param,String wxMpAppId) { return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxMpAppId + "&redirect_uri="+ redirectUrl + "&response_type=code&scope=" + type + "&state=" + param + "#wechat_redirect"; } /** * 網頁授權 */ public String getOauthAccessToken(String code,String wxMpAppId,String wxMpAppSecret) { return "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxMpAppId + "&secret=" + wxMpAppSecret+ "&code=" + code + "&grant_type=" + ConstantManager.GRANT_TYPE; } /** * 重新整理網頁授權accessToken */ public String refreshAccessToken(String refreshToken,String wxMpAppId) { return "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + wxMpAppId+ "&grant_type=refresh_token&refresh_token=" + refreshToken.trim(); } /** * 微信使用者詳細資訊 accessToken:網頁授權accessToken openId:使用者openid 通過授權獲取 */ public String getUserInfo(String accessToken, String openId) { return "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken.trim() + "&openid=" + openId.trim()+ "&lang=zh_CN"; } /** * 獲取使用者詳細資訊 通過全域性accessToken獲取 */ public String getUserInfoByGlobalToken(String globalToken, String openId) { return "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + globalToken + "&openid=" + openId+ "&lang=zh_CN "; } /** * 長短連線轉換 */ public String getShortUrl(String accessToken) { return "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" + accessToken; } /** * 獲取模版列表 */ public String getModelList(String accessToken) { return "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=" + accessToken; } /** * 傳送模版訊息 */ public String sendModelMessage(String accessToken) { return "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken; } /** * 獲取模版設定的行業資訊 */ public String getModelIndustry(String accessToken) { return "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=" + accessToken; } /** * 獲取jsapi簽名 */ public String getJsApiConfig(String accessToken){ return "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token"; } /** * 獲取關注的使用者列表 */ public String getUserList(String accessToken,String openId){ if(StringUtils.isBlank(openId)){ return "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken; }else{ return "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken+"&next_openid="+openId; } } /** * 建立二維碼ticket */ public String createQrcodeTicket(String accessToken){ return " https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken; } /** * 通過ticket換取二維碼 */ public String showQrcode(String ticket){ return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket; } /** * 微信web登入url */ public String getWxWebLoginUrl(String type,String redirectUrl,String param,String wxOpenAppId){ return "https://open.weixin.qq.com/connect/qrconnect?appid="+wxOpenAppId+"&redirect_uri="+redirectUrl+"&response_type=code&scope="+type+"&state="+param+"#wechat_redirect"; } /** * 微信卡包ticket */ public String getTicketUrl(String accessToken){ return "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=wx_card"; } /** * 新增客服帳號 * @description * * @author tjz * * @param accessToken * @return * * @time 2018年2月2日 上午9:54:20 */ public String addKfAccountUrl(String accessToken){ return "https://api.weixin.qq.com/customservice/kfaccount/add?access_token"; } /** * 獲取所有客服帳號 */ public String getKfListUrl(String accessToken){ return "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token"; } /** * 傳送客服訊息 */ public String getSendMessageUrl(String accessToken){ return "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken; } /** * 獲取QQ登入Url */ public String getQqLoginUrl(String appId,String callbackUrl,String state,String scope){ return "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="+appId+"&redirect_uri="+callbackUrl+"&state="+state+"&scope="+scope; } /** * 獲取PC版QQ登入accessToken */ public String getQqLoginAccessTokenByPcUrl(String qqAppId,String qqAppKey,String code,String redirectUri){ return "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id="+qqAppId+"&client_secret="+qqAppKey+"&code="+code+"&redirect_uri="+redirectUri; } /** * 獲取WAP版QQ登入accessToken */ public String getQqLoginAccessTokenByWapUrl(String qqAppId,String qqAppKey,String code,String redirectUri){ return "https://graph.z.qq.com/moc2/token?grant_type=authorization_code&client_id="+qqAppId+"&client_secret="+qqAppKey+"&code="+code+"&redirect_uri="+redirectUri; } /** * 重新整理pc授權accessToken */ public String refreshPcQqAccessTokenUrl(String qqAppId,String qqAppKey,String refreshToken){ return "https://graph.qq.com/oauth2.0/token?grant_type=refresh_token&client_id="+qqAppId+"&client_secret="+qqAppKey+"&refresh_token="+refreshToken; } /** * 重新整理wap授權accessToken */ public String refreshWapQqAccessTokenUrl(String qqAppId,String qqAppKey,String refreshToken){ return "https://graph.z.qq.com/moc2/token?grant_type=refresh_token&client_id="+qqAppId+"&client_secret="+qqAppKey+"&refresh_token="+refreshToken; } /** * 獲取PC qq使用者openId */ public String getPcQqUserInfoByAccessTokenUrl(String accessToken){ return "https://graph.qq.com/oauth2.0/me?access_token="+accessToken; } /** * 獲取wap qq使用者openId */ public String getWapQqUserInfoByAccessTokenUrl(String accessToken){ return "https://graph.z.qq.com/moc2/me?access_token="+accessToken; } /** * 獲取QQ使用者詳細資訊 */ public String getQqUserInfoByAccessTokenAndOpenId(String appId,String accessToken,String openId){ return "https://graph.qq.com/user/get_user_info?access_token="+accessToken+"&oauth_consumer_key="+appId+"&openid="+openId; }
}
QqConfig.java
package com.qq.config;
public class QqConfig {
public static String appId="101245606";
public static String appKey="2b58836429gs225s7cd7cda1df429beb";
}
QqAccessToken.java
package com.qq.entity;
import java.io.Serializable;
/**
-
qq登入accessToken物件
-
@description
-
@author tjz
-
@time 2018年2月23日 下午4:24:21
*/
public class QqAccessToken implements Serializable{private static final long serialVersionUID = -8019689330896908016L;
private String expires_in;
private String refresh_token;
private String access_token;
public String getExpires_in() {
return expires_in;
}public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}public String getRefresh_token() {
return refresh_token;
}public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}public String getAccess_token() {
return access_token;
}public void setAccess_token(String access_token) {
this.access_token = access_token;
}
}
QqUserInfoEntity.java
package com.qq.entity;
import java.io.Serializable;
/**
-
qq使用者資訊實體類
-
@description
-
@author tjz
-
@time 2018年2月24日 下午1:24:06
*/
public class QqUserInfoEntity implements Serializable {private static final long serialVersionUID = 366914903331900232L;
private int ret;
private String msg;
private int is_lost;
private String nickname;
private String gender;
private String province;
private String city;
private String year;
private String figureurl;
private String figureurl_1;
private String figureurl_2;
private String figureurl_qq_1;
private String figureurl_qq_2;
private String is_yellow_vip;
private String vip;
private String yellow_vip_level;
private String level;
private String is_yellow_year_vip;
private String openId;
public void setRet(int ret) {
this.ret = ret;
}public int getRet() {
return ret;
}public void setMsg(String msg) {
this.msg = msg;
}public String getMsg() {
return msg;
}public void setIs_lost(int is_lost) {
this.is_lost = is_lost;
}public int getIs_lost() {
return is_lost;
}public void setNickname(String nickname) {
this.nickname = nickname;
}public String getNickname() {
return nickname;
}public void setGender(String gender) {
this.gender = gender;
}public String getGender() {
return gender;
}public void setProvince(String province) {
this.province = province;
}public String getProvince() {
return province;
}public void setCity(String city) {
this.city = city;
}public String getCity() {
return city;
}public void setYear(String year) {
this.year = year;
}public String getYear() {
return year;
}public void setFigureurl(String figureurl) {
this.figureurl = figureurl;
}public String getFigureurl() {
return figureurl;
}public void setFigureurl_1(String figureurl_1) {
this.figureurl_1 = figureurl_1;
}public String getFigureurl_1() {
return figureurl_1;
}public void setFigureurl_2(String figureurl_2) {
this.figureurl_2 = figureurl_2;
}public String getFigureurl_2() {
return figureurl_2;
}public void setFigureurl_qq_1(String figureurl_qq_1) {
this.figureurl_qq_1 = figureurl_qq_1;
}public String getFigureurl_qq_1() {
return figureurl_qq_1;
}public void setFigureurl_qq_2(String figureurl_qq_2) {
this.figureurl_qq_2 = figureurl_qq_2;
}public String getFigureurl_qq_2() {
return figureurl_qq_2;
}public void setIs_yellow_vip(String is_yellow_vip) {
this.is_yellow_vip = is_yellow_vip;
}public String getIs_yellow_vip() {
return is_yellow_vip;
}public void setVip(String vip) {
this.vip = vip;
}public String getVip() {
return vip;
}public void setYellow_vip_level(String yellow_vip_level) {
this.yellow_vip_level = yellow_vip_level;
}public String getYellow_vip_level() {
return yellow_vip_level;
}public void setLevel(String level) {
this.level = level;
}public String getLevel() {
return level;
}public void setIs_yellow_year_vip(String is_yellow_year_vip) {
this.is_yellow_year_vip = is_yellow_year_vip;
}public String getIs_yellow_year_vip() {
return is_yellow_year_vip;
}public String getOpenId() {
return openId;
}public void setOpenId(String openId) {
this.openId = openId;
}
}
CallbackServlet.java
package com.qq.servlet;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.qq.common.ConstantManager;
import com.qq.common.UrlConfig;
import com.qq.config.QqConfig;
import com.qq.entity.QqAccessToken;
import com.qq.entity.QqUserInfoEntity;
import com.qq.util.HttpUtil;
import com.qq.util.MapUtil;
import com.qq.util.UrlUtil;
public class CallbackServlet extends HttpServlet {
private static final long serialVersionUID = 8113114647105374282L;
private UrlConfig urlConfig = new UrlConfig();
public CallbackServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = request.getParameter("code");
String state = request.getParameter("state");
try {
String url = urlConfig.getQqLoginAccessTokenByPcUrl(QqConfig.appId, QqConfig.appKey, code, ConstantManager.QQCALLBACKURL);
String result = HttpUtil.doGet(url);
if (StringUtils.isBlank(result)) {
System.out.println("QQ回撥處理失敗!獲取accessToken時無返回結果!");
return;
}
Map<String, Object> map = UrlUtil.URLRequest(result);
if (map == null) {
System.out.println("QQ回撥處理失敗!獲取accessToken結果轉map失敗!");
return;
}
if (map.size() == 0) {
System.out.println("QQ回撥處理失敗!獲取accessToken結果轉map失敗!");
return;
}
QqAccessToken accessToken = (QqAccessToken) MapUtil.mapToObject(map, QqAccessToken.class);
if (accessToken == null) {
System.out.println("QQ回撥處理失敗!獲取accessToken結果map轉物件失敗!");
return;
}
if (StringUtils.isBlank(accessToken.getAccess_token())) {
System.out.println("QQ回撥處理失敗!獲取accessToken失敗!");
return;
}
String openId = getUserOpenIdByAccessToken(accessToken.getAccess_token());
JSONObject resultJson = getUserInfoByOpenId(QqConfig.appId, accessToken.getAccess_token(), openId);
System.out.println("qq授權結束********************");
System.out.println(resultJson.toJSONString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通過騰訊授權code獲取使用者資訊
*/
public String getUserOpenIdByAccessToken(String accessToken) {
String openId = null;
try {
String url = urlConfig.getPcQqUserInfoByAccessTokenUrl(accessToken);
String result = HttpUtil.doGet(url);
if (StringUtils.isBlank(result)) {
throw new Exception("獲取openId的失敗");
}
Matcher m = Pattern.compile("\"openid\"\\s*:\\s*\"(\\w+)\"").matcher(result);
if (m.find()) {
openId = m.group(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return openId;
}
public JSONObject getUserInfoByOpenId(String appId, String accessToken, String openId) {
JSONObject returnJson = new JSONObject();
try {
String result = HttpUtil.doGet(urlConfig.getQqUserInfoByAccessTokenAndOpenId(appId, accessToken, openId));
JSONObject jsonObject = JSONObject.parseObject(result);
Integer errcode = jsonObject.getInteger("ret");
if (errcode != 0) {
System.out.println("授權過期,請重新授權!");
return null;
}
QqUserInfoEntity userEntity = JSONObject.toJavaObject(jsonObject, QqUserInfoEntity.class);
returnJson.put("code", 0);
returnJson.put("data", userEntity);
returnJson.put("msg", "獲取使用者資訊成功!");
} catch (Exception e) {
e.printStackTrace();
}
return returnJson;
}
public void init() throws ServletException {
}
}
QqLoginServlet.java
package com.qq.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.qq.common.ConstantManager;
import com.qq.common.UrlConfig;
import com.qq.config.QqConfig;
public class QqLoginServlet extends HttpServlet {
private static final long serialVersionUID = -7802576126667825322L;
private UrlConfig urlConfig=new UrlConfig();
public QqLoginServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = urlConfig.getQqLoginUrl(QqConfig.appId, ConstantManager.QQCALLBACKURL, null, ConstantManager.OAUTH_QQ_USER_INFO);
response.sendRedirect(url);
}
public void init() throws ServletException {
}
}
HttpUtil.java
package com.qq.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class HttpUtil {
private static final Logger logger = LogManager.getLogger(HttpUtil.class);
private static String charset = "utf-8";
private Integer connectTimeout = null;
private Integer socketTimeout = null;
private static String proxyHost = null;
private static Integer proxyPort = null;
private static HttpClient httpClient = null;
private static GetMethod getMethod = null;
private static PostMethod postMethod = null;
/**
* POST請求 json
* @param url
* @param params
* @return
*/
public static String doPostJson(String url, String params,boolean header) {
try {
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
PostMethod postMethod = new PostMethod(url);
if(header){
postMethod.setRequestHeader("Content-Type","application/json");
postMethod.setRequestHeader("Authorization","Basic YWRtaW46YWRtaW4=");
}
if(params != null && !params.trim().equals("")) {
RequestEntity requestEntity = new StringRequestEntity(params,"application/json","UTF-8");
postMethod.setRequestEntity(requestEntity);
}
postMethod.releaseConnection();
httpClient.executeMethod(postMethod);
BufferedReader reader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while((str = reader.readLine())!=null){
stringBuffer.append(str);
}
logger.info("傳送POST_JSON請求");
logger.info("URL:"+url);
logger.info("引數:"+params);
logger.info("響應結果:"+stringBuffer.toString());
return stringBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 傳送Get請求
*
* @param url
* @return
* @throws Exception
*/
public static String doGet(String url) throws Exception {
URL localURL = new URL(url);
URLConnection connection = openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
try {
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
logger.info("傳送GET請求");
logger.info("URL:"+url);
logger.info("響應結果:"+resultBuffer.toString());
return resultBuffer.toString();
}
/**
* 傳送Post請求
*
* @param url
* @param parameterMap
* @return
* @throws Exception
*/
public static String doPost(String url, Map parameterMap) throws Exception {
StringBuffer parameterBuffer = new StringBuffer();
if (parameterMap != null) {
Iterator iterator = parameterMap.keySet().iterator();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if (parameterMap.get(key) != null) {
value = (String) parameterMap.get(key);
} else {
value = "";
}
parameterBuffer.append(key).append("=").append(value);
if (iterator.hasNext()) {
parameterBuffer.append("&");
}
}
}
URL localURL = new URL(url);
URLConnection connection = openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(parameterBuffer.toString());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
logger.info("傳送POST請求");
logger.info("URL:"+url);
logger.info("引數:"+parameterBuffer.toString());
logger.info("響應結果:"+resultBuffer.toString());
return resultBuffer.toString();
}
private static URLConnection openConnection(URL localURL) throws IOException {
URLConnection connection;
if (proxyHost != null && proxyPort != null) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
connection = localURL.openConnection(proxy);
} else {
connection = localURL.openConnection();
}
return connection;
}
/**
* Render request according setting
*
* @param request
*/
private void renderRequest(URLConnection connection) {
if (connectTimeout != null) {
connection.setConnectTimeout(connectTimeout);
}
if (socketTimeout != null) {
connection.setReadTimeout(socketTimeout);
}
}
/*
* Getter & Setter
*/
public Integer getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(Integer connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Integer getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(Integer socketTimeout) {
this.socketTimeout = socketTimeout;
}
public String getProxyHost() {
return proxyHost;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public Integer getProxyPort() {
return proxyPort;
}
public void setProxyPort(Integer proxyPort) {
this.proxyPort = proxyPort;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
}
MapUtil.java
package com.qq.util;
import java.util.Map;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;
/**
-
map資料操作工具類
-
@description
-
@author tjz
-
@time 2018年2月23日 下午4:31:38
*/
public class MapUtil {/**
-
map轉物件
-
@description
-
@author tjz
-
@param map
-
@param beanClass
-
@return
-
@throws Exception
-
@time 2018年2月23日 下午4:31:28
*/
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;Object obj = beanClass.newInstance();
BeanUtils.populate(obj, map);
return obj;
}
/**
-
物件轉map
-
@description
-
@author tjz
-
@param obj
-
@return
-
@time 2018年2月23日 下午4:31:34
*/
public static Map<?, ?> objectToMap(Object obj) {
if (obj == null)
return null;return new BeanMap(obj);
}
}
-
UrlUtil.java
package com.qq.util;
import java.util.HashMap;
import java.util.Map;
public class UrlUtil {
/**
* 解析url形式的引數值
* @description
*
* @author tjz
*
* @param strUrlParam
* @return
*
* @time 2018年2月23日 下午4:19:01
*/
public static Map<String, Object> URLRequest(String strUrlParam) {
Map<String, Object> mapRequest = new HashMap<String, Object>();
String[] arrSplit = null;
arrSplit = strUrlParam.split("[&]");
for (String strSplit : arrSplit) {
String[] arrSplitEqual = null;
arrSplitEqual = strSplit.split("[=]");
// 解析出鍵值
if (arrSplitEqual.length > 1) {
// 正確解析
mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
} else {
if (arrSplitEqual[0] != "") {
// 只有引數沒有值,不加入
mapRequest.put(arrSplitEqual[0], "");
}
}
}
return mapRequest;
}
public static void main(String[] args) {
Map<String, Object> map = URLRequest("access_token=E1875F86B99F561D60803C27B096E347&expires_in=7776000&refresh_token=B69F4950FF3035B711BC70DC85B6F343");
System.out.println(map);
System.out.println(map.size());
System.out.println(map.toString());
}
}
最效果:
需要現成原始碼的朋友,可以加Q76949433,提供技術支援!