From 8dc4b5d7d64ea0e209451afb2f2a4369db071970 Mon Sep 17 00:00:00 2001
From: "Yangkai.Shen" <237497819@qq.com>
Date: Wed, 25 Dec 2019 18:28:18 +0800
Subject: [PATCH] =?UTF-8?q?:recycle:=20=E6=8A=BD=E5=8F=96=20HTTP=EF=BC=8C?=
=?UTF-8?q?=E5=85=B7=E4=BD=93=E5=AE=9E=E7=8E=B0=E4=BA=A4=E7=BB=99=E4=BD=BF?=
=?UTF-8?q?=E7=94=A8=E8=80=85=EF=BC=8C=E8=A7=A3=E8=80=A6=20hutool-http?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
pom.xml | 10 +-
.../zhyd/oauth/request/AuthBaiduRequest.java | 18 +-
.../zhyd/oauth/request/AuthCodingRequest.java | 9 +-
.../zhyd/oauth/request/AuthCsdnRequest.java | 9 +-
.../oauth/request/AuthDefaultRequest.java | 39 ++--
.../oauth/request/AuthDingTalkRequest.java | 11 +-
.../zhyd/oauth/request/AuthDouyinRequest.java | 12 +-
.../zhyd/oauth/request/AuthElemeRequest.java | 87 ++++----
.../oauth/request/AuthFacebookRequest.java | 8 +-
.../zhyd/oauth/request/AuthGiteeRequest.java | 8 +-
.../zhyd/oauth/request/AuthGithubRequest.java | 11 +-
.../zhyd/oauth/request/AuthGitlabRequest.java | 9 +-
.../zhyd/oauth/request/AuthGoogleRequest.java | 15 +-
.../zhyd/oauth/request/AuthHuaweiRequest.java | 59 +++---
.../oauth/request/AuthKujialeRequest.java | 24 +--
.../oauth/request/AuthLinkedinRequest.java | 45 ++--
.../oauth/request/AuthMeituanRequest.java | 49 +++--
.../me/zhyd/oauth/request/AuthMiRequest.java | 17 +-
.../oauth/request/AuthMicrosoftRequest.java | 30 +--
.../oauth/request/AuthOschinaRequest.java | 9 +-
.../oauth/request/AuthPinterestRequest.java | 12 +-
.../me/zhyd/oauth/request/AuthQqRequest.java | 49 ++---
.../zhyd/oauth/request/AuthRenrenRequest.java | 11 +-
.../request/AuthStackOverflowRequest.java | 24 ++-
.../zhyd/oauth/request/AuthTaobaoRequest.java | 9 +-
.../oauth/request/AuthTeambitionRequest.java | 42 ++--
.../request/AuthTencentCloudRequest.java | 9 +-
.../oauth/request/AuthToutiaoRequest.java | 9 +-
.../oauth/request/AuthTwitterRequest.java | 100 ++++-----
.../request/AuthWeChatEnterpriseRequest.java | 18 +-
.../oauth/request/AuthWeChatMpRequest.java | 15 +-
.../oauth/request/AuthWeChatOpenRequest.java | 11 +-
.../zhyd/oauth/request/AuthWeiboRequest.java | 28 +--
.../java/me/zhyd/oauth/utils/AuthChecker.java | 6 +-
.../java/me/zhyd/oauth/utils/Base64Utils.java | 197 ++++++++++++++++++
...obalAuthUtil.java => GlobalAuthUtils.java} | 53 ++---
.../java/me/zhyd/oauth/utils/StringUtils.java | 39 +++-
.../java/me/zhyd/oauth/utils/UrlBuilder.java | 14 +-
.../me/zhyd/oauth/sdk/ThirdPartSdkTest.java | 40 ++--
...UtilTest.java => GlobalAuthUtilsTest.java} | 63 +++---
40 files changed, 715 insertions(+), 513 deletions(-)
create mode 100644 src/main/java/me/zhyd/oauth/utils/Base64Utils.java
rename src/main/java/me/zhyd/oauth/utils/{GlobalAuthUtil.java => GlobalAuthUtils.java} (83%)
rename src/test/java/me/zhyd/oauth/utils/{GlobalAuthUtilTest.java => GlobalAuthUtilsTest.java} (72%)
diff --git a/pom.xml b/pom.xml
index 41b0f11..81f188e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -6,7 +6,7 @@
me.zhyd.oauth
JustAuth
- 1.13.2
+ 1.14.0-SNAPSHOT
JustAuth
https://gitee.com/yadong.zhang/JustAuth
@@ -60,7 +60,7 @@
2.20
1.6
false
- 5.0.5
+ 1.0
1.18.10
4.11
1.2.62
@@ -76,9 +76,9 @@
true
- cn.hutool
- hutool-http
- ${hutool-version}
+ com.xkcoding.http
+ simple-http
+ ${simple-http.version}
junit
diff --git a/src/main/java/me/zhyd/oauth/request/AuthBaiduRequest.java b/src/main/java/me/zhyd/oauth/request/AuthBaiduRequest.java
index 05341e1..e21f923 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthBaiduRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthBaiduRequest.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -34,14 +33,13 @@ public class AuthBaiduRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
+ String response = doPostAuthorizationCode(authCallback.getCode());
return getAuthToken(response);
}
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- String userInfo = response.body();
+ String userInfo = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(userInfo);
this.checkResponse(object);
return AuthUser.builder()
@@ -63,8 +61,8 @@ public class AuthBaiduRequest extends AuthDefaultRequest {
@Override
public AuthResponse revoke(AuthToken authToken) {
- HttpResponse response = doGetRevoke(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetRevoke(authToken);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
// 返回1表示取消授权成功,否则失败
AuthResponseStatus status = object.getIntValue("result") == 1 ? AuthResponseStatus.SUCCESS : AuthResponseStatus.FAILURE;
@@ -79,7 +77,7 @@ public class AuthBaiduRequest extends AuthDefaultRequest {
.queryParam("client_id", this.config.getClientId())
.queryParam("client_secret", this.config.getClientSecret())
.build();
- HttpResponse response = HttpRequest.get(refreshUrl).execute();
+ String response = HttpUtil.get(refreshUrl);
return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode())
.data(this.getAuthToken(response))
@@ -116,8 +114,8 @@ public class AuthBaiduRequest extends AuthDefaultRequest {
}
}
- private AuthToken getAuthToken(HttpResponse response) {
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ private AuthToken getAuthToken(String response) {
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
diff --git a/src/main/java/me/zhyd/oauth/request/AuthCodingRequest.java b/src/main/java/me/zhyd/oauth/request/AuthCodingRequest.java
index 7bb8e1f..3285203 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthCodingRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthCodingRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -30,8 +29,8 @@ public class AuthCodingRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doGetAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
@@ -42,8 +41,8 @@ public class AuthCodingRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
object = object.getJSONObject("data");
diff --git a/src/main/java/me/zhyd/oauth/request/AuthCsdnRequest.java b/src/main/java/me/zhyd/oauth/request/AuthCsdnRequest.java
index d11f953..fab84f3 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthCsdnRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthCsdnRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -30,16 +29,16 @@ public class AuthCsdnRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doPostAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder().accessToken(accessTokenObject.getString("access_token")).build();
}
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
return AuthUser.builder()
.uuid(object.getString("username"))
diff --git a/src/main/java/me/zhyd/oauth/request/AuthDefaultRequest.java b/src/main/java/me/zhyd/oauth/request/AuthDefaultRequest.java
index c02c571..b4e431d 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthDefaultRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthDefaultRequest.java
@@ -1,7 +1,6 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -208,62 +207,62 @@ public abstract class AuthDefaultRequest implements AuthRequest {
* 通用的 authorizationCode 协议
*
* @param code code码
- * @return HttpResponse
+ * @return Response
*/
- protected HttpResponse doPostAuthorizationCode(String code) {
- return HttpRequest.post(accessTokenUrl(code)).execute();
+ protected String doPostAuthorizationCode(String code) {
+ return HttpUtil.post(accessTokenUrl(code));
}
/**
* 通用的 authorizationCode 协议
*
* @param code code码
- * @return HttpResponse
+ * @return Response
*/
- protected HttpResponse doGetAuthorizationCode(String code) {
- return HttpRequest.get(accessTokenUrl(code)).execute();
+ protected String doGetAuthorizationCode(String code) {
+ return HttpUtil.get(accessTokenUrl(code));
}
/**
* 通用的 用户信息
*
* @param authToken token封装
- * @return HttpResponse
+ * @return Response
*/
@Deprecated
- protected HttpResponse doPostUserInfo(AuthToken authToken) {
- return HttpRequest.post(userInfoUrl(authToken)).execute();
+ protected String doPostUserInfo(AuthToken authToken) {
+ return HttpUtil.post(userInfoUrl(authToken));
}
/**
* 通用的 用户信息
*
* @param authToken token封装
- * @return HttpResponse
+ * @return Response
*/
- protected HttpResponse doGetUserInfo(AuthToken authToken) {
- return HttpRequest.get(userInfoUrl(authToken)).execute();
+ protected String doGetUserInfo(AuthToken authToken) {
+ return HttpUtil.get(userInfoUrl(authToken));
}
/**
* 通用的post形式的取消授权方法
*
* @param authToken token封装
- * @return HttpResponse
+ * @return Response
*/
@Deprecated
- protected HttpResponse doPostRevoke(AuthToken authToken) {
- return HttpRequest.post(revokeUrl(authToken)).execute();
+ protected String doPostRevoke(AuthToken authToken) {
+ return HttpUtil.post(revokeUrl(authToken));
}
/**
* 通用的post形式的取消授权方法
*
* @param authToken token封装
- * @return HttpResponse
+ * @return Response
*/
- protected HttpResponse doGetRevoke(AuthToken authToken) {
- return HttpRequest.get(revokeUrl(authToken)).execute();
+ protected String doGetRevoke(AuthToken authToken) {
+ return HttpUtil.get(revokeUrl(authToken));
}
}
diff --git a/src/main/java/me/zhyd/oauth/request/AuthDingTalkRequest.java b/src/main/java/me/zhyd/oauth/request/AuthDingTalkRequest.java
index 6ff0aa1..af10d9a 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthDingTalkRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthDingTalkRequest.java
@@ -1,9 +1,8 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -12,7 +11,7 @@ import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
-import me.zhyd.oauth.utils.GlobalAuthUtil;
+import me.zhyd.oauth.utils.GlobalAuthUtils;
import me.zhyd.oauth.utils.UrlBuilder;
/**
@@ -41,8 +40,8 @@ public class AuthDingTalkRequest extends AuthDefaultRequest {
String code = authToken.getAccessCode();
JSONObject param = new JSONObject();
param.put("tmp_auth_code", code);
- HttpResponse response = HttpRequest.post(userInfoUrl(authToken)).body(param.toJSONString()).execute();
- JSONObject object = JSON.parseObject(response.body());
+ String response = HttpUtil.post(userInfoUrl(authToken), param.toJSONString());
+ JSONObject object = JSON.parseObject(response);
if (object.getIntValue("errcode") != 0) {
throw new AuthException(object.getString("errmsg"));
}
@@ -89,7 +88,7 @@ public class AuthDingTalkRequest extends AuthDefaultRequest {
protected String userInfoUrl(AuthToken authToken) {
// 根据timestamp, appSecret计算签名值
String timestamp = System.currentTimeMillis() + "";
- String urlEncodeSignature = GlobalAuthUtil.generateDingTalkSignature(config.getClientSecret(), timestamp);
+ String urlEncodeSignature = GlobalAuthUtils.generateDingTalkSignature(config.getClientSecret(), timestamp);
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("signature", urlEncodeSignature)
diff --git a/src/main/java/me/zhyd/oauth/request/AuthDouyinRequest.java b/src/main/java/me/zhyd/oauth/request/AuthDouyinRequest.java
index 51f9c5d..86461b0 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthDouyinRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthDouyinRequest.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -39,8 +38,8 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject userInfoObject = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject userInfoObject = JSONObject.parseObject(response);
this.checkResponse(userInfoObject);
JSONObject dataObj = userInfoObject.getJSONObject("data");
return AuthUser.builder()
@@ -85,9 +84,8 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
* @return token对象
*/
private AuthToken getToken(String accessTokenUrl) {
- HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
- String accessTokenStr = response.body();
- JSONObject object = JSONObject.parseObject(accessTokenStr);
+ String response = HttpUtil.post(accessTokenUrl);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
JSONObject dataObj = object.getJSONObject("data");
return AuthToken.builder()
diff --git a/src/main/java/me/zhyd/oauth/request/AuthElemeRequest.java b/src/main/java/me/zhyd/oauth/request/AuthElemeRequest.java
index 4a8c3b7..7ecdb93 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthElemeRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthElemeRequest.java
@@ -1,9 +1,9 @@
package me.zhyd.oauth.request;
-import cn.hutool.core.codec.Base64;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
+import com.xkcoding.http.constants.Constants;
+import com.xkcoding.http.support.HttpHeader;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -14,7 +14,8 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
-import me.zhyd.oauth.utils.GlobalAuthUtil;
+import me.zhyd.oauth.utils.Base64Utils;
+import me.zhyd.oauth.utils.GlobalAuthUtils;
import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.utils.UuidUtils;
@@ -31,6 +32,9 @@ import java.util.Map;
*/
public class AuthElemeRequest extends AuthDefaultRequest {
+ private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded;charset=UTF-8";
+ private static final String CONTENT_TYPE_JSON = "application/json; charset=utf-8";
+
public AuthElemeRequest(AuthConfig config) {
super(config, AuthDefaultSource.ELEME);
}
@@ -41,18 +45,15 @@ public class AuthElemeRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
+ Map form = new HashMap<>(4);
+ form.put("client_id", config.getClientId());
+ form.put("redirect_uri", config.getRedirectUri());
+ form.put("code", authCallback.getCode());
+ form.put("grant_type", "authorization_code");
- HttpRequest request = HttpRequest.post(source.accessToken())
- .form("client_id", config.getClientId())
- .form("redirect_uri", config.getRedirectUri())
- .form("code", authCallback.getCode())
- .form("grant_type", "authorization_code");
-
- // 设置header
- this.setHeader(request);
-
- HttpResponse response = request.execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ HttpHeader httpHeader = this.buildHeader(CONTENT_TYPE_FORM, this.getRequestId(), true);
+ String response = HttpUtil.post(source.accessToken(), form, httpHeader, false);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
@@ -75,11 +76,11 @@ public class AuthElemeRequest extends AuthDefaultRequest {
Map metasHashMap = new HashMap<>();
metasHashMap.put("app_key", config.getClientId());
metasHashMap.put("timestamp", timestamp);
- String signature = GlobalAuthUtil.generateElemeSignature(config.getClientId(), config.getClientSecret(), timestamp, action, authToken.getAccessToken(), parameters);
+ String signature = GlobalAuthUtils.generateElemeSignature(config.getClientId(), config.getClientSecret(), timestamp, action, authToken
+ .getAccessToken(), parameters);
String requestId = this.getRequestId();
-
Map paramsMap = new HashMap<>();
paramsMap.put("nop", "1.0.0");
paramsMap.put("id", requestId);
@@ -89,15 +90,10 @@ public class AuthElemeRequest extends AuthDefaultRequest {
paramsMap.put("params", parameters);
paramsMap.put("signature", signature);
- HttpRequest request = HttpRequest.post(source.userInfo())
- .body(JSONObject.toJSONBytes(paramsMap));
-
- // 设置header
- this.setHeader(request, "application/json; charset=utf-8", requestId);
+ HttpHeader httpHeader = this.buildHeader(CONTENT_TYPE_JSON, requestId, false);
+ String response = HttpUtil.post(source.userInfo(), JSONObject.toJSONString(paramsMap), httpHeader);
- HttpResponse response = request.execute();
-
- JSONObject object = JSONObject.parseObject(response.body());
+ JSONObject object = JSONObject.parseObject(response);
// 校验请求
if (object.containsKey("name")) {
@@ -121,15 +117,14 @@ public class AuthElemeRequest extends AuthDefaultRequest {
@Override
public AuthResponse refresh(AuthToken oldToken) {
- HttpRequest request = HttpRequest.post(source.refresh())
- .form("refresh_token", oldToken.getRefreshToken())
- .form("grant_type", "refresh_token");
+ Map form = new HashMap<>(2);
+ form.put("refresh_token", oldToken.getRefreshToken());
+ form.put("grant_type", "refresh_token");
- // 设置header
- this.setHeader(request);
+ HttpHeader httpHeader = this.buildHeader(CONTENT_TYPE_FORM, this.getRequestId(), true);
+ String response = HttpUtil.post(source.refresh(), form, httpHeader, false);
- HttpResponse response = request.execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
@@ -146,29 +141,27 @@ public class AuthElemeRequest extends AuthDefaultRequest {
@Override
public String authorize(String state) {
- return UrlBuilder.fromBaseUrl(super.authorize(state))
- .queryParam("scope", "all")
- .build();
+ return UrlBuilder.fromBaseUrl(super.authorize(state)).queryParam("scope", "all").build();
}
private String getBasic(String appKey, String appSecret) {
StringBuilder sb = new StringBuilder();
- String encodeToString = Base64.encode((appKey + ":" + appSecret).getBytes());
+ String encodeToString = Base64Utils.encode((appKey + ":" + appSecret).getBytes());
sb.append("Basic").append(" ").append(encodeToString);
return sb.toString();
}
- private void setHeader(HttpRequest request) {
- setHeader(request, "application/x-www-form-urlencoded;charset=UTF-8", getRequestId());
- request.header("Authorization", this.getBasic(config.getClientId(), config.getClientSecret()));
- }
-
- private void setHeader(HttpRequest request, String contentType, String requestId) {
- request.header("Accept", "text/xml,text/javascript,text/html")
- .header("Content-Type", contentType)
- .header("Accept-Encoding", "gzip")
- .header("User-Agent", "eleme-openapi-java-sdk")
- .header("x-eleme-requestid", requestId);
+ private HttpHeader buildHeader(String contentType, String requestId, boolean auth) {
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Accept", "text/xml,text/javascript,text/html");
+ httpHeader.add(Constants.CONTENT_TYPE, contentType);
+ httpHeader.add("Accept-Encoding", "gzip");
+ httpHeader.add("User-Agent", "eleme-openapi-java-sdk");
+ httpHeader.add("x-eleme-requestid", requestId);
+ if (auth) {
+ httpHeader.add("Authorization", this.getBasic(config.getClientId(), config.getClientSecret()));
+ }
+ return httpHeader;
}
private String getRequestId() {
diff --git a/src/main/java/me/zhyd/oauth/request/AuthFacebookRequest.java b/src/main/java/me/zhyd/oauth/request/AuthFacebookRequest.java
index c65d1f2..0de5389 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthFacebookRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthFacebookRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -30,8 +29,8 @@ public class AuthFacebookRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doPostAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
@@ -42,8 +41,7 @@ public class AuthFacebookRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- String userInfo = response.body();
+ String userInfo = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(userInfo);
this.checkResponse(object);
return AuthUser.builder()
diff --git a/src/main/java/me/zhyd/oauth/request/AuthGiteeRequest.java b/src/main/java/me/zhyd/oauth/request/AuthGiteeRequest.java
index 7c930f1..9f95f0b 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthGiteeRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthGiteeRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -29,8 +28,8 @@ public class AuthGiteeRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doPostAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
@@ -43,8 +42,7 @@ public class AuthGiteeRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- String userInfo = response.body();
+ String userInfo = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(userInfo);
this.checkResponse(object);
return AuthUser.builder()
diff --git a/src/main/java/me/zhyd/oauth/request/AuthGithubRequest.java b/src/main/java/me/zhyd/oauth/request/AuthGithubRequest.java
index cbe0032..98a616b 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthGithubRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthGithubRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -10,7 +9,7 @@ import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
-import me.zhyd.oauth.utils.GlobalAuthUtil;
+import me.zhyd.oauth.utils.GlobalAuthUtils;
import java.util.Map;
@@ -32,8 +31,8 @@ public class AuthGithubRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
- Map res = GlobalAuthUtil.parseStringToMap(response.body());
+ String response = doPostAuthorizationCode(authCallback.getCode());
+ Map res = GlobalAuthUtils.parseStringToMap(response);
this.checkResponse(res.containsKey("error"), res.get("error_description"));
@@ -46,8 +45,8 @@ public class AuthGithubRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object.containsKey("error"), object.getString("error_description"));
diff --git a/src/main/java/me/zhyd/oauth/request/AuthGitlabRequest.java b/src/main/java/me/zhyd/oauth/request/AuthGitlabRequest.java
index 3bab918..7c5f0b4 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthGitlabRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthGitlabRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -30,8 +29,8 @@ public class AuthGitlabRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doPostAuthorizationCode(authCallback.getCode());
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
@@ -46,8 +45,8 @@ public class AuthGitlabRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
diff --git a/src/main/java/me/zhyd/oauth/request/AuthGoogleRequest.java b/src/main/java/me/zhyd/oauth/request/AuthGoogleRequest.java
index 43a5c04..242db08 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthGoogleRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthGoogleRequest.java
@@ -1,8 +1,8 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
+import com.xkcoding.http.support.HttpHeader;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -31,8 +31,8 @@ public class AuthGoogleRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doPostAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
@@ -45,10 +45,9 @@ public class AuthGoogleRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = HttpRequest.post(userInfoUrl(authToken))
- .header("Authorization", "Bearer " + authToken.getAccessToken())
- .execute();
- String userInfo = response.body();
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Authorization", "Bearer " + authToken.getAccessToken());
+ String userInfo = HttpUtil.post(userInfoUrl(authToken), null, httpHeader);
JSONObject object = JSONObject.parseObject(userInfo);
this.checkResponse(object);
return AuthUser.builder()
diff --git a/src/main/java/me/zhyd/oauth/request/AuthHuaweiRequest.java b/src/main/java/me/zhyd/oauth/request/AuthHuaweiRequest.java
index 099467c..4544a92 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthHuaweiRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthHuaweiRequest.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -14,6 +13,9 @@ import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.UrlBuilder;
+import java.util.HashMap;
+import java.util.Map;
+
import static me.zhyd.oauth.enums.AuthResponseStatus.SUCCESS;
/**
@@ -43,13 +45,15 @@ public class AuthHuaweiRequest extends AuthDefaultRequest {
*/
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpRequest request = HttpRequest.post(source.accessToken())
- .form("grant_type", "authorization_code")
- .form("code", authCallback.getAuthorization_code())
- .form("client_id", config.getClientId())
- .form("client_secret", config.getClientSecret())
- .form("redirect_uri", config.getRedirectUri());
- return getAuthToken(request);
+ Map form = new HashMap<>(5);
+ form.put("grant_type", "authorization_code");
+ form.put("code", authCallback.getAuthorization_code());
+ form.put("client_id", config.getClientId());
+ form.put("client_secret", config.getClientSecret());
+ form.put("redirect_uri", config.getRedirectUri());
+
+ String response = HttpUtil.post(source.accessToken(), form, false);
+ return getAuthToken(response);
}
/**
@@ -61,13 +65,14 @@ public class AuthHuaweiRequest extends AuthDefaultRequest {
*/
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = HttpRequest.post(source.userInfo())
- .form("nsp_ts", System.currentTimeMillis())
- .form("access_token", authToken.getAccessToken())
- .form("nsp_fmt", "JS")
- .form("nsp_svc", "OpenUP.User.getInfo")
- .execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ Map form = new HashMap<>(4);
+ form.put("nsp_ts", System.currentTimeMillis() + "");
+ form.put("access_token", authToken.getAccessToken());
+ form.put("nsp_fmt", "JS");
+ form.put("nsp_svc", "OpenUP.User.getInfo");
+
+ String response = HttpUtil.post(source.userInfo(), form, false);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
@@ -92,20 +97,18 @@ public class AuthHuaweiRequest extends AuthDefaultRequest {
*/
@Override
public AuthResponse refresh(AuthToken authToken) {
- HttpRequest request = HttpRequest.post(source.refresh())
- .form("client_id", config.getClientId())
- .form("client_secret", config.getClientSecret())
- .form("refresh_token", authToken.getRefreshToken())
- .form("grant_type", "refresh_token");
- return AuthResponse.builder()
- .code(SUCCESS.getCode())
- .data(getAuthToken(request))
- .build();
+ Map form = new HashMap<>(4);
+ form.put("client_id", config.getClientId());
+ form.put("client_secret", config.getClientSecret());
+ form.put("refresh_token", authToken.getRefreshToken());
+ form.put("grant_type", "refresh_token");
+
+ String response = HttpUtil.post(source.refresh(), form, false);
+ return AuthResponse.builder().code(SUCCESS.getCode()).data(getAuthToken(response)).build();
}
- private AuthToken getAuthToken(HttpRequest request) {
- HttpResponse response = request.execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ private AuthToken getAuthToken(String response) {
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
diff --git a/src/main/java/me/zhyd/oauth/request/AuthKujialeRequest.java b/src/main/java/me/zhyd/oauth/request/AuthKujialeRequest.java
index f43fd30..d15786f 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthKujialeRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthKujialeRequest.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -66,11 +65,11 @@ public class AuthKujialeRequest extends AuthDefaultRequest {
@Override
public AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
+ String response = doPostAuthorizationCode(authCallback.getCode());
return getAuthToken(response);
}
- private AuthToken getAuthToken(HttpResponse response) {
+ private AuthToken getAuthToken(String response) {
JSONObject accessTokenObject = checkResponse(response);
JSONObject resultObject = accessTokenObject.getJSONObject("d");
return AuthToken.builder()
@@ -80,9 +79,8 @@ public class AuthKujialeRequest extends AuthDefaultRequest {
.build();
}
- private JSONObject checkResponse(HttpResponse response) {
- String accessTokenStr = response.body();
- JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr);
+ private JSONObject checkResponse(String response) {
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
if (!"0".equals(accessTokenObject.getString("c"))) {
throw new AuthException(accessTokenObject.getString("m"));
}
@@ -92,11 +90,11 @@ public class AuthKujialeRequest extends AuthDefaultRequest {
@Override
public AuthUser getUserInfo(AuthToken authToken) {
String openId = this.getOpenId(authToken);
- HttpResponse response = HttpRequest.get(UrlBuilder.fromBaseUrl(source.userInfo())
+ String response = HttpUtil.get(UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("open_id", openId)
- .build()).execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ .build());
+ JSONObject object = JSONObject.parseObject(response);
if (!"0".equals(object.getString("c"))) {
throw new AuthException(object.getString("m"));
}
@@ -119,16 +117,16 @@ public class AuthKujialeRequest extends AuthDefaultRequest {
* @return openId
*/
private String getOpenId(AuthToken authToken) {
- HttpResponse response = HttpRequest.get(UrlBuilder.fromBaseUrl("https://oauth.kujiale.com/oauth2/auth/user")
+ String response = HttpUtil.get(UrlBuilder.fromBaseUrl("https://oauth.kujiale.com/oauth2/auth/user")
.queryParam("access_token", authToken.getAccessToken())
- .build()).execute();
+ .build());
JSONObject accessTokenObject = checkResponse(response);
return accessTokenObject.getString("d");
}
@Override
public AuthResponse refresh(AuthToken authToken) {
- HttpResponse response = HttpRequest.post(refreshTokenUrl(authToken.getRefreshToken())).execute();
+ String response = HttpUtil.post(refreshTokenUrl(authToken.getRefreshToken()));
return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(getAuthToken(response)).build();
}
}
diff --git a/src/main/java/me/zhyd/oauth/request/AuthLinkedinRequest.java b/src/main/java/me/zhyd/oauth/request/AuthLinkedinRequest.java
index 886ad09..470dd2f 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthLinkedinRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthLinkedinRequest.java
@@ -1,10 +1,11 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
+import com.xkcoding.http.HttpUtil;
+import com.xkcoding.http.constants.Constants;
+import com.xkcoding.http.support.HttpHeader;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -43,12 +44,13 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken();
- HttpResponse response = HttpRequest.get(userInfoUrl(authToken))
- .header("Host", "api.linkedin.com")
- .header("Connection", "Keep-Alive")
- .header("Authorization", "Bearer " + accessToken)
- .execute();
- JSONObject userInfoObject = JSONObject.parseObject(response.body());
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Host", "api.linkedin.com");
+ httpHeader.add("Connection", "Keep-Alive");
+ httpHeader.add("Authorization", "Bearer " + accessToken);
+
+ String response = HttpUtil.get(userInfoUrl(authToken), null, httpHeader, false);
+ JSONObject userInfoObject = JSONObject.parseObject(response);
this.checkResponse(userInfoObject);
@@ -121,13 +123,16 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
* @return 用户的邮箱地址
*/
private String getUserEmail(String accessToken) {
- HttpResponse emailResponse = HttpRequest.get("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))")
- .header("Host", "api.linkedin.com")
- .header("Connection", "Keep-Alive")
- .header("Authorization", "Bearer " + accessToken)
- .execute();
- JSONObject emailObj = JSONObject.parseObject(emailResponse.body());
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Host", "api.linkedin.com");
+ httpHeader.add("Connection", "Keep-Alive");
+ httpHeader.add("Authorization", "Bearer " + accessToken);
+
+ String emailResponse = HttpUtil.get("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))");
+ JSONObject emailObj = JSONObject.parseObject(emailResponse);
+
this.checkResponse(emailObj);
+
Object obj = JSONPath.eval(emailObj, "$['elements'][0]['handle~']['emailAddress']");
return null == obj ? null : (String) obj;
}
@@ -172,12 +177,12 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
* @return token对象
*/
private AuthToken getToken(String accessTokenUrl) {
- HttpResponse response = HttpRequest.post(accessTokenUrl)
- .header("Host", "www.linkedin.com")
- .contentType("application/x-www-form-urlencoded")
- .execute();
- String accessTokenStr = response.body();
- JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr);
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Host", "www.linkedin.com");
+ httpHeader.add(Constants.CONTENT_TYPE, "application/x-www-form-urlencoded");
+
+ String response = HttpUtil.post(accessTokenUrl, null, httpHeader);
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
diff --git a/src/main/java/me/zhyd/oauth/request/AuthMeituanRequest.java b/src/main/java/me/zhyd/oauth/request/AuthMeituanRequest.java
index ddfed4d..d4e2e91 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthMeituanRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthMeituanRequest.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -15,6 +14,9 @@ import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.UrlBuilder;
+import java.util.HashMap;
+import java.util.Map;
+
/**
* 美团登录
*
@@ -33,13 +35,14 @@ public class AuthMeituanRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = HttpRequest.post(source.accessToken())
- .form("app_id", config.getClientId())
- .form("secret", config.getClientSecret())
- .form("code", authCallback.getCode())
- .form("grant_type", "authorization_code")
- .execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ Map form = new HashMap<>(4);
+ form.put("app_id", config.getClientId());
+ form.put("secret", config.getClientSecret());
+ form.put("code", authCallback.getCode());
+ form.put("grant_type", "authorization_code");
+
+ String response = HttpUtil.post(source.accessToken(), form, false);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
@@ -52,12 +55,13 @@ public class AuthMeituanRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = HttpRequest.post(source.userInfo())
- .form("app_id", config.getClientId())
- .form("secret", config.getClientSecret())
- .form("access_token", authToken.getAccessToken())
- .execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ Map form = new HashMap<>(3);
+ form.put("app_id", config.getClientId());
+ form.put("secret", config.getClientSecret());
+ form.put("access_token", authToken.getAccessToken());
+
+ String response = HttpUtil.post(source.userInfo(), form, false);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
@@ -74,13 +78,14 @@ public class AuthMeituanRequest extends AuthDefaultRequest {
@Override
public AuthResponse refresh(AuthToken oldToken) {
- HttpResponse response = HttpRequest.post(source.refresh())
- .form("app_id", config.getClientId())
- .form("secret", config.getClientSecret())
- .form("refresh_token", oldToken.getRefreshToken())
- .form("grant_type", "refresh_token")
- .execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ Map form = new HashMap<>(4);
+ form.put("app_id", config.getClientId());
+ form.put("secret", config.getClientSecret());
+ form.put("refresh_token", oldToken.getRefreshToken());
+ form.put("grant_type", "refresh_token");
+
+ String response = HttpUtil.post(source.refresh(), form, false);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
diff --git a/src/main/java/me/zhyd/oauth/request/AuthMiRequest.java b/src/main/java/me/zhyd/oauth/request/AuthMiRequest.java
index 97fce22..ee85c51 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthMiRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthMiRequest.java
@@ -1,9 +1,8 @@
package me.zhyd.oauth.request;
-import cn.hutool.core.util.StrUtil;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
+import com.xkcoding.http.constants.Constants;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -42,8 +41,8 @@ public class AuthMiRequest extends AuthDefaultRequest {
}
private AuthToken getToken(String accessTokenUrl) {
- HttpResponse response = HttpRequest.get(accessTokenUrl).execute();
- String jsonStr = StrUtil.replace(response.body(), PREFIX, StrUtil.EMPTY);
+ String response = HttpUtil.get(accessTokenUrl);
+ String jsonStr = response.replace(PREFIX, Constants.EMPTY);
JSONObject accessTokenObject = JSONObject.parseObject(jsonStr);
if (accessTokenObject.containsKey("error")) {
@@ -65,9 +64,9 @@ public class AuthMiRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
// 获取用户信息
- HttpResponse userResponse = doGetUserInfo(authToken);
+ String userResponse = doGetUserInfo(authToken);
- JSONObject userProfile = JSONObject.parseObject(userResponse.body());
+ JSONObject userProfile = JSONObject.parseObject(userResponse);
if ("error".equalsIgnoreCase(userProfile.getString("result"))) {
throw new AuthException(userProfile.getString("description"));
}
@@ -89,8 +88,8 @@ public class AuthMiRequest extends AuthDefaultRequest {
String emailPhoneUrl = MessageFormat.format("{0}?clientId={1}&token={2}", "https://open.account.xiaomi.com/user/phoneAndEmail", config
.getClientId(), authToken.getAccessToken());
- HttpResponse emailResponse = HttpRequest.get(emailPhoneUrl).execute();
- JSONObject userEmailPhone = JSONObject.parseObject(emailResponse.body());
+ String emailResponse = HttpUtil.get(emailPhoneUrl);
+ JSONObject userEmailPhone = JSONObject.parseObject(emailResponse);
if (!"error".equalsIgnoreCase(userEmailPhone.getString("result"))) {
JSONObject emailPhone = userEmailPhone.getJSONObject("data");
authUser.setEmail(emailPhone.getString("email"));
diff --git a/src/main/java/me/zhyd/oauth/request/AuthMicrosoftRequest.java b/src/main/java/me/zhyd/oauth/request/AuthMicrosoftRequest.java
index d15179d..c8a132d 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthMicrosoftRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthMicrosoftRequest.java
@@ -1,8 +1,10 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
+import com.xkcoding.http.constants.Constants;
+import com.xkcoding.http.support.HttpHeader;
+import com.xkcoding.http.util.MapUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -15,7 +17,7 @@ import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.UrlBuilder;
-import static me.zhyd.oauth.utils.GlobalAuthUtil.parseQueryToMap;
+import java.util.Map;
/**
* 微软登录
@@ -44,13 +46,14 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest {
* @return token对象
*/
private AuthToken getToken(String accessTokenUrl) {
- HttpResponse response = HttpRequest.post(accessTokenUrl)
- .header("Host", "https://login.microsoftonline.com")
- .contentType("application/x-www-form-urlencoded")
- .form(parseQueryToMap(accessTokenUrl))
- .execute();
- String accessTokenStr = response.body();
- JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr);
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Host", "https://login.microsoftonline.com");
+ httpHeader.add(Constants.CONTENT_TYPE, "application/x-www-form-urlencoded");
+
+ Map form = MapUtil.parseStringToMap(accessTokenUrl, false);
+
+ String response = HttpUtil.post(accessTokenUrl, form, httpHeader, false);
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
@@ -79,8 +82,11 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest {
String token = authToken.getAccessToken();
String tokenType = authToken.getTokenType();
String jwt = tokenType + " " + token;
- HttpResponse response = HttpRequest.get(userInfoUrl(authToken)).header("Authorization", jwt).execute();
- String userInfo = response.body();
+
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Authorization", jwt);
+
+ String userInfo = HttpUtil.get(userInfoUrl(authToken), null, httpHeader, false);
JSONObject object = JSONObject.parseObject(userInfo);
this.checkResponse(object);
return AuthUser.builder()
diff --git a/src/main/java/me/zhyd/oauth/request/AuthOschinaRequest.java b/src/main/java/me/zhyd/oauth/request/AuthOschinaRequest.java
index 4733820..4019ad8 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthOschinaRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthOschinaRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -30,8 +29,8 @@ public class AuthOschinaRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doPostAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
@@ -43,8 +42,8 @@ public class AuthOschinaRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
return AuthUser.builder()
.uuid(object.getString("id"))
diff --git a/src/main/java/me/zhyd/oauth/request/AuthPinterestRequest.java b/src/main/java/me/zhyd/oauth/request/AuthPinterestRequest.java
index 0f73e1e..6efadd5 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthPinterestRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthPinterestRequest.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.AuthUserGender;
@@ -36,8 +35,8 @@ public class AuthPinterestRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doPostAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
@@ -48,8 +47,9 @@ public class AuthPinterestRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
String userinfoUrl = userInfoUrl(authToken);
- HttpResponse response = HttpRequest.get(userinfoUrl).setFollowRedirects(true).execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ // TODO: 是否需要 .setFollowRedirects(true)
+ String response = HttpUtil.get(userinfoUrl);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
JSONObject userObj = object.getJSONObject("data");
return AuthUser.builder()
diff --git a/src/main/java/me/zhyd/oauth/request/AuthQqRequest.java b/src/main/java/me/zhyd/oauth/request/AuthQqRequest.java
index c63ec6e..0107345 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthQqRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthQqRequest.java
@@ -1,9 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.core.util.StrUtil;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -14,7 +12,7 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
-import me.zhyd.oauth.utils.GlobalAuthUtil;
+import me.zhyd.oauth.utils.GlobalAuthUtils;
import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UrlBuilder;
@@ -38,21 +36,21 @@ public class AuthQqRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
+ String response = doGetAuthorizationCode(authCallback.getCode());
return getAuthToken(response);
}
@Override
public AuthResponse refresh(AuthToken authToken) {
- HttpResponse response = HttpRequest.get(refreshTokenUrl(authToken.getRefreshToken())).execute();
+ String response = HttpUtil.get(refreshTokenUrl(authToken.getRefreshToken()));
return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(getAuthToken(response)).build();
}
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
String openId = this.getOpenId(authToken);
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject object = JSONObject.parseObject(response);
if (object.getIntValue("ret") != 0) {
throw new AuthException(object.getString("msg"));
}
@@ -82,27 +80,22 @@ public class AuthQqRequest extends AuthDefaultRequest {
* @return openId
*/
private String getOpenId(AuthToken authToken) {
- HttpResponse response = HttpRequest.get(UrlBuilder.fromBaseUrl("https://graph.qq.com/oauth2.0/me")
+ String response = HttpUtil.get(UrlBuilder.fromBaseUrl("https://graph.qq.com/oauth2.0/me")
.queryParam("access_token", authToken.getAccessToken())
.queryParam("unionid", config.isUnionId() ? 1 : 0)
- .build()).execute();
- if (response.isOk()) {
- String body = response.body();
- String removePrefix = StrUtil.replace(body, "callback(", "");
- String removeSuffix = StrUtil.replace(removePrefix, ");", "");
- String openId = StrUtil.trim(removeSuffix);
- JSONObject object = JSONObject.parseObject(openId);
- if (object.containsKey("error")) {
- throw new AuthException(object.get("error") + ":" + object.get("error_description"));
- }
- authToken.setOpenId(object.getString("openid"));
- if (object.containsKey("unionid")) {
- authToken.setUnionId(object.getString("unionid"));
- }
- return StringUtils.isEmpty(authToken.getUnionId()) ? authToken.getOpenId() : authToken.getUnionId();
+ .build());
+ String removePrefix = response.replace("callback(", "");
+ String removeSuffix = removePrefix.replace(");", "");
+ String openId = removeSuffix.trim();
+ JSONObject object = JSONObject.parseObject(openId);
+ if (object.containsKey("error")) {
+ throw new AuthException(object.get("error") + ":" + object.get("error_description"));
}
-
- throw new AuthException("request error");
+ authToken.setOpenId(object.getString("openid"));
+ if (object.containsKey("unionid")) {
+ authToken.setUnionId(object.getString("unionid"));
+ }
+ return StringUtils.isEmpty(authToken.getUnionId()) ? authToken.getOpenId() : authToken.getUnionId();
}
/**
@@ -120,8 +113,8 @@ public class AuthQqRequest extends AuthDefaultRequest {
.build();
}
- private AuthToken getAuthToken(HttpResponse response) {
- Map accessTokenObject = GlobalAuthUtil.parseStringToMap(response.body());
+ private AuthToken getAuthToken(String response) {
+ Map accessTokenObject = GlobalAuthUtils.parseStringToMap(response);
if (!accessTokenObject.containsKey("access_token") || accessTokenObject.containsKey("code")) {
throw new AuthException(accessTokenObject.get("msg"));
}
diff --git a/src/main/java/me/zhyd/oauth/request/AuthRenrenRequest.java b/src/main/java/me/zhyd/oauth/request/AuthRenrenRequest.java
index 736cf4a..889a418 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthRenrenRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthRenrenRequest.java
@@ -1,9 +1,8 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.AuthUserGender;
@@ -42,8 +41,8 @@ public class AuthRenrenRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject userObj = JSONObject.parseObject(response.body()).getJSONObject("response");
+ String response = doGetUserInfo(authToken);
+ JSONObject userObj = JSONObject.parseObject(response).getJSONObject("response");
return AuthUser.builder()
.uuid(userObj.getString("id"))
@@ -65,8 +64,8 @@ public class AuthRenrenRequest extends AuthDefaultRequest {
}
private AuthToken getToken(String url) {
- HttpResponse response = HttpRequest.post(url).execute();
- JSONObject jsonObject = JSONObject.parseObject(response.body());
+ String response = HttpUtil.post(url);
+ JSONObject jsonObject = JSONObject.parseObject(response);
if (jsonObject.containsKey("error")) {
throw new AuthException("Failed to get token from Renren: " + jsonObject);
}
diff --git a/src/main/java/me/zhyd/oauth/request/AuthStackOverflowRequest.java b/src/main/java/me/zhyd/oauth/request/AuthStackOverflowRequest.java
index ac77076..c98be60 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthStackOverflowRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthStackOverflowRequest.java
@@ -1,8 +1,10 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
+import com.xkcoding.http.constants.Constants;
+import com.xkcoding.http.support.HttpHeader;
+import com.xkcoding.http.util.MapUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.AuthUserGender;
@@ -12,8 +14,9 @@ import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.UrlBuilder;
+import java.util.Map;
+
import static me.zhyd.oauth.config.AuthDefaultSource.STACK_OVERFLOW;
-import static me.zhyd.oauth.utils.GlobalAuthUtil.parseQueryToMap;
/**
* Stack Overflow登录
@@ -34,11 +37,12 @@ public class AuthStackOverflowRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = accessTokenUrl(authCallback.getCode());
- HttpResponse response = HttpRequest.post(accessTokenUrl)
- .contentType("application/x-www-form-urlencoded")
- .form(parseQueryToMap(accessTokenUrl))
- .execute();
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ Map form = MapUtil.parseStringToMap(accessTokenUrl, false);
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add(Constants.CONTENT_TYPE, "application/x-www-form-urlencoded");
+ String response = HttpUtil.post(accessTokenUrl, form, httpHeader, false);
+
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
@@ -54,8 +58,8 @@ public class AuthStackOverflowRequest extends AuthDefaultRequest {
.queryParam("site", "stackoverflow")
.queryParam("key", this.config.getStackOverflowKey())
.build();
- HttpResponse response = HttpRequest.get(userInfoUrl).execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = HttpUtil.get(userInfoUrl);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
JSONObject userObj = object.getJSONArray("items").getJSONObject(0);
diff --git a/src/main/java/me/zhyd/oauth/request/AuthTaobaoRequest.java b/src/main/java/me/zhyd/oauth/request/AuthTaobaoRequest.java
index a457759..6d8ef09 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthTaobaoRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthTaobaoRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -10,7 +9,7 @@ import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
-import me.zhyd.oauth.utils.GlobalAuthUtil;
+import me.zhyd.oauth.utils.GlobalAuthUtils;
import me.zhyd.oauth.utils.UrlBuilder;
/**
@@ -36,8 +35,8 @@ public class AuthTaobaoRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doPostAuthorizationCode(authToken.getAccessCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doPostAuthorizationCode(authToken.getAccessCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
if (accessTokenObject.containsKey("error")) {
throw new AuthException(accessTokenObject.getString("error_description"));
}
@@ -47,7 +46,7 @@ public class AuthTaobaoRequest extends AuthDefaultRequest {
authToken.setUid(accessTokenObject.getString("taobao_user_id"));
authToken.setOpenId(accessTokenObject.getString("taobao_open_uid"));
- String nick = GlobalAuthUtil.urlDecode(accessTokenObject.getString("taobao_user_nick"));
+ String nick = GlobalAuthUtils.urlDecode(accessTokenObject.getString("taobao_user_nick"));
return AuthUser.builder()
.uuid(accessTokenObject.getString("taobao_user_id"))
.username(nick)
diff --git a/src/main/java/me/zhyd/oauth/request/AuthTeambitionRequest.java b/src/main/java/me/zhyd/oauth/request/AuthTeambitionRequest.java
index 5b20618..ebfd2a2 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthTeambitionRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthTeambitionRequest.java
@@ -1,8 +1,8 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
+import com.xkcoding.http.support.HttpHeader;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -14,6 +14,9 @@ import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
+import java.util.HashMap;
+import java.util.Map;
+
/**
* Teambition授权登录
*
@@ -36,13 +39,14 @@ public class AuthTeambitionRequest extends AuthDefaultRequest {
*/
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = HttpRequest.post(source.accessToken())
- .form("client_id", config.getClientId())
- .form("client_secret", config.getClientSecret())
- .form("code", authCallback.getCode())
- .form("grant_type", "code")
- .execute();
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ Map form = new HashMap<>(4);
+ form.put("client_id", config.getClientId());
+ form.put("client_secret", config.getClientSecret());
+ form.put("code", authCallback.getCode());
+ form.put("grant_type", "code");
+
+ String response = HttpUtil.post(source.accessToken(), form, false);
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
@@ -56,10 +60,11 @@ public class AuthTeambitionRequest extends AuthDefaultRequest {
protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken();
- HttpResponse response = HttpRequest.get(source.userInfo())
- .header("Authorization", "OAuth2 " + accessToken)
- .execute();
- JSONObject object = JSONObject.parseObject(response.body());
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Authorization", "OAuth2 " + accessToken);
+
+ String response = HttpUtil.get(source.userInfo(), null, httpHeader, false);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
@@ -83,11 +88,12 @@ public class AuthTeambitionRequest extends AuthDefaultRequest {
public AuthResponse refresh(AuthToken oldToken) {
String uid = oldToken.getUid();
String refreshToken = oldToken.getRefreshToken();
- HttpResponse response = HttpRequest.post(source.refresh())
- .form("_userId", uid)
- .form("refresh_token", refreshToken)
- .execute();
- JSONObject refreshTokenObject = JSONObject.parseObject(response.body());
+
+ Map form = new HashMap<>(2);
+ form.put("_userId", uid);
+ form.put("refresh_token", refreshToken);
+ String response = HttpUtil.post(source.refresh(), form, false);
+ JSONObject refreshTokenObject = JSONObject.parseObject(response);
this.checkResponse(refreshTokenObject);
diff --git a/src/main/java/me/zhyd/oauth/request/AuthTencentCloudRequest.java b/src/main/java/me/zhyd/oauth/request/AuthTencentCloudRequest.java
index b319a60..1f5ea31 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthTencentCloudRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthTencentCloudRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -30,8 +29,8 @@ public class AuthTencentCloudRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doGetAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
@@ -42,8 +41,8 @@ public class AuthTencentCloudRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
object = object.getJSONObject("data");
diff --git a/src/main/java/me/zhyd/oauth/request/AuthToutiaoRequest.java b/src/main/java/me/zhyd/oauth/request/AuthToutiaoRequest.java
index 53edf33..999f774 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthToutiaoRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthToutiaoRequest.java
@@ -1,6 +1,5 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
@@ -31,8 +30,8 @@ public class AuthToutiaoRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = doGetAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
@@ -45,9 +44,9 @@ public class AuthToutiaoRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse userResponse = doGetUserInfo(authToken);
+ String userResponse = doGetUserInfo(authToken);
- JSONObject userProfile = JSONObject.parseObject(userResponse.body());
+ JSONObject userProfile = JSONObject.parseObject(userResponse);
this.checkResponse(userProfile);
diff --git a/src/main/java/me/zhyd/oauth/request/AuthTwitterRequest.java b/src/main/java/me/zhyd/oauth/request/AuthTwitterRequest.java
index 0a40a97..0e3d3a9 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthTwitterRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthTwitterRequest.java
@@ -1,23 +1,24 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
+import com.xkcoding.http.constants.Constants;
+import com.xkcoding.http.support.HttpHeader;
+import com.xkcoding.http.util.MapUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
-import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
-import me.zhyd.oauth.utils.GlobalAuthUtil;
+import me.zhyd.oauth.utils.GlobalAuthUtils;
import me.zhyd.oauth.utils.UrlBuilder;
import java.util.HashMap;
import java.util.Map;
import static me.zhyd.oauth.config.AuthDefaultSource.TWITTER;
-import static me.zhyd.oauth.utils.GlobalAuthUtil.generateTwitterSignature;
-import static me.zhyd.oauth.utils.GlobalAuthUtil.urlEncode;
+import static me.zhyd.oauth.utils.GlobalAuthUtils.generateTwitterSignature;
+import static me.zhyd.oauth.utils.GlobalAuthUtils.urlEncode;
/**
* Twitter登录
@@ -46,19 +47,21 @@ public class AuthTwitterRequest extends AuthDefaultRequest {
public AuthToken getRequestToken() {
String baseUrl = "https://api.twitter.com/oauth/request_token";
- Map oauthParams = buildOauthParams();
+ Map oauthParams = buildOauthParams();
oauthParams.put("oauth_callback", config.getRedirectUri());
oauthParams.put("oauth_signature", generateTwitterSignature(oauthParams, "POST", baseUrl, config.getClientSecret(), null));
String header = buildHeader(oauthParams);
- HttpResponse requestToken = HttpRequest.post(baseUrl).header("Authorization", header).execute();
- checkResponse(requestToken);
- Map res = GlobalAuthUtil.parseQueryToMap(requestToken.body());
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Authorization", header);
+ String requestToken = HttpUtil.post(baseUrl, null, httpHeader);
+
+ Map res = MapUtil.parseStringToMap(requestToken, false);
return AuthToken.builder()
- .oauthToken(res.get("oauth_token").toString())
- .oauthTokenSecret(res.get("oauth_token_secret").toString())
- .oauthCallbackConfirmed(Boolean.valueOf(res.get("oauth_callback_confirmed").toString()))
+ .oauthToken(res.get("oauth_token"))
+ .oauthTokenSecret(res.get("oauth_token_secret"))
+ .oauthCallbackConfirmed(Boolean.valueOf(res.get("oauth_callback_confirmed")))
.build();
}
@@ -70,45 +73,51 @@ public class AuthTwitterRequest extends AuthDefaultRequest {
*/
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- Map oauthParams = buildOauthParams();
+ Map oauthParams = buildOauthParams();
oauthParams.put("oauth_token", authCallback.getOauthToken());
oauthParams.put("oauth_verifier", authCallback.getOauthVerifier());
- oauthParams.put("oauth_signature", generateTwitterSignature(oauthParams, "POST", source.accessToken(), config.getClientSecret(), authCallback.getOauthToken()));
+ oauthParams.put("oauth_signature", generateTwitterSignature(oauthParams, "POST", source.accessToken(), config.getClientSecret(), authCallback
+ .getOauthToken()));
String header = buildHeader(oauthParams);
- HttpResponse response = HttpRequest.post(source.accessToken())
- .header("Authorization", header)
- .header("Content-Type", "application/x-www-form-urlencoded")
- .form("oauth_verifier", authCallback.getOauthVerifier())
- .execute();
- checkResponse(response);
- Map requestToken = GlobalAuthUtil.parseQueryToMap(response.body());
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Authorization", header);
+ httpHeader.add(Constants.CONTENT_TYPE, "application/x-www-form-urlencoded");
+
+ Map form = new HashMap<>(1);
+ form.put("oauth_verifier", authCallback.getOauthVerifier());
+ String response = HttpUtil.post(source.accessToken(), form, httpHeader, false);
+
+ Map requestToken = MapUtil.parseStringToMap(response, false);
return AuthToken.builder()
- .oauthToken(requestToken.get("oauth_token").toString())
- .oauthTokenSecret(requestToken.get("oauth_token_secret").toString())
- .userId(requestToken.get("user_id").toString())
- .screenName(requestToken.get("screen_name").toString())
+ .oauthToken(requestToken.get("oauth_token"))
+ .oauthTokenSecret(requestToken.get("oauth_token_secret"))
+ .userId(requestToken.get("user_id"))
+ .screenName(requestToken.get("screen_name"))
.build();
}
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- Map queryParams = new HashMap<>();
+ Map queryParams = new HashMap<>();
queryParams.put("user_id", authToken.getUserId());
queryParams.put("screen_name", authToken.getScreenName());
- queryParams.put("include_entities", true);
+ queryParams.put("include_entities", Boolean.toString(true));
- Map oauthParams = buildOauthParams();
+ Map oauthParams = buildOauthParams();
oauthParams.put("oauth_token", authToken.getOauthToken());
- Map params = new HashMap<>(oauthParams);
+ Map params = new HashMap<>(oauthParams);
params.putAll(queryParams);
- oauthParams.put("oauth_signature", generateTwitterSignature(params, "GET", source.userInfo(), config.getClientSecret(), authToken.getOauthTokenSecret()));
+ oauthParams.put("oauth_signature", generateTwitterSignature(params, "GET", source.userInfo(), config.getClientSecret(), authToken
+ .getOauthTokenSecret()));
String header = buildHeader(oauthParams);
- HttpResponse response = HttpRequest.get(userInfoUrl(authToken)).header("Authorization", header).execute();
- checkResponse(response);
- JSONObject userInfo = JSONObject.parseObject(response.body());
+
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Authorization", header);
+ String response = HttpUtil.get(userInfoUrl(authToken), null, httpHeader, false);
+ JSONObject userInfo = JSONObject.parseObject(response);
return AuthUser.builder()
.uuid(userInfo.getString("id_str"))
@@ -132,35 +141,26 @@ public class AuthTwitterRequest extends AuthDefaultRequest {
.build();
}
- private Map buildOauthParams() {
- Map params = new HashMap<>();
+ private Map buildOauthParams() {
+ Map params = new HashMap<>(5);
params.put("oauth_consumer_key", config.getClientId());
- params.put("oauth_nonce", GlobalAuthUtil.generateNonce(32));
+ params.put("oauth_nonce", GlobalAuthUtils.generateNonce(32));
params.put("oauth_signature_method", "HMAC-SHA1");
- params.put("oauth_timestamp", GlobalAuthUtil.getTimestamp());
+ params.put("oauth_timestamp", GlobalAuthUtils.getTimestamp());
params.put("oauth_version", "1.0");
return params;
}
- private String buildHeader(Map oauthParams) {
+ private String buildHeader(Map oauthParams) {
final StringBuilder sb = new StringBuilder(PREAMBLE);
- for (Map.Entry param : oauthParams.entrySet()) {
+ for (Map.Entry param : oauthParams.entrySet()) {
if (sb.length() > PREAMBLE.length()) {
sb.append(", ");
}
- sb.append(param.getKey())
- .append("=\"")
- .append(urlEncode(param.getValue().toString()))
- .append('"');
+ sb.append(param.getKey()).append("=\"").append(urlEncode(param.getValue())).append('"');
}
return sb.toString();
}
-
- private void checkResponse(HttpResponse response) {
- if (!response.isOk()) {
- throw new AuthException(response.body());
- }
- }
}
diff --git a/src/main/java/me/zhyd/oauth/request/AuthWeChatEnterpriseRequest.java b/src/main/java/me/zhyd/oauth/request/AuthWeChatEnterpriseRequest.java
index b1d1f72..93fdade 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthWeChatEnterpriseRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthWeChatEnterpriseRequest.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -12,7 +11,6 @@ import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
-import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UrlBuilder;
/**
@@ -40,7 +38,7 @@ public class AuthWeChatEnterpriseRequest extends AuthDefaultRequest {
*/
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doGetAuthorizationCode(accessTokenUrl(authCallback.getCode()));
+ String response = doGetAuthorizationCode(accessTokenUrl(authCallback.getCode()));
JSONObject object = this.checkResponse(response);
@@ -53,7 +51,7 @@ public class AuthWeChatEnterpriseRequest extends AuthDefaultRequest {
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
- HttpResponse response = doGetUserInfo(authToken);
+ String response = doGetUserInfo(authToken);
JSONObject object = this.checkResponse(response);
// 返回 OpenId 或其他,均代表非当前企业用户,不支持
@@ -61,7 +59,7 @@ public class AuthWeChatEnterpriseRequest extends AuthDefaultRequest {
throw new AuthException(AuthResponseStatus.UNIDENTIFIED_PLATFORM, source);
}
String userId = object.getString("UserId");
- HttpResponse userDetailResponse = getUserDetail(authToken.getAccessToken(), userId);
+ String userDetailResponse = getUserDetail(authToken.getAccessToken(), userId);
JSONObject userDetail = this.checkResponse(userDetailResponse);
return AuthUser.builder()
@@ -83,8 +81,8 @@ public class AuthWeChatEnterpriseRequest extends AuthDefaultRequest {
* @param response 请求结果
* @return 如果请求结果正常,则返回JSONObject
*/
- private JSONObject checkResponse(HttpResponse response) {
- JSONObject object = JSONObject.parseObject(response.body());
+ private JSONObject checkResponse(String response) {
+ JSONObject object = JSONObject.parseObject(response);
if (object.containsKey("errcode") && object.getIntValue("errcode") != 0) {
throw new AuthException(object.getString("errmsg"), source);
@@ -145,12 +143,12 @@ public class AuthWeChatEnterpriseRequest extends AuthDefaultRequest {
* @param userId 企业内用户id
* @return 用户详情
*/
- private HttpResponse getUserDetail(String accessToken, String userId) {
+ private String getUserDetail(String accessToken, String userId) {
String userDetailUrl = UrlBuilder.fromBaseUrl("https://qyapi.weixin.qq.com/cgi-bin/user/get")
.queryParam("access_token", accessToken)
.queryParam("userid", userId)
.build();
- return HttpRequest.get(userDetailUrl).execute();
+ return HttpUtil.get(userDetailUrl);
}
}
diff --git a/src/main/java/me/zhyd/oauth/request/AuthWeChatMpRequest.java b/src/main/java/me/zhyd/oauth/request/AuthWeChatMpRequest.java
index fcac5d8..29ab5ec 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthWeChatMpRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthWeChatMpRequest.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -13,7 +12,7 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
-import me.zhyd.oauth.utils.GlobalAuthUtil;
+import me.zhyd.oauth.utils.GlobalAuthUtils;
import me.zhyd.oauth.utils.UrlBuilder;
/**
@@ -46,8 +45,8 @@ public class AuthWeChatMpRequest extends AuthDefaultRequest {
protected AuthUser getUserInfo(AuthToken authToken) {
String openId = authToken.getOpenId();
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
@@ -95,8 +94,8 @@ public class AuthWeChatMpRequest extends AuthDefaultRequest {
* @return token对象
*/
private AuthToken getToken(String accessTokenUrl) {
- HttpResponse response = HttpRequest.get(accessTokenUrl).execute();
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = HttpUtil.get(accessTokenUrl);
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
@@ -120,7 +119,7 @@ public class AuthWeChatMpRequest extends AuthDefaultRequest {
public String authorize(String state) {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("appid", config.getClientId())
- .queryParam("redirect_uri", GlobalAuthUtil.urlEncode(config.getRedirectUri()))
+ .queryParam("redirect_uri", GlobalAuthUtils.urlEncode(config.getRedirectUri()))
.queryParam("response_type", "code")
.queryParam("scope", "snsapi_userinfo")
.queryParam("state", getRealState(state).concat("#wechat_redirect"))
diff --git a/src/main/java/me/zhyd/oauth/request/AuthWeChatOpenRequest.java b/src/main/java/me/zhyd/oauth/request/AuthWeChatOpenRequest.java
index 1513677..241b9c0 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthWeChatOpenRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthWeChatOpenRequest.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -45,8 +44,8 @@ public class AuthWeChatOpenRequest extends AuthDefaultRequest {
protected AuthUser getUserInfo(AuthToken authToken) {
String openId = authToken.getOpenId();
- HttpResponse response = doGetUserInfo(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetUserInfo(authToken);
+ JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
@@ -94,8 +93,8 @@ public class AuthWeChatOpenRequest extends AuthDefaultRequest {
* @return token对象
*/
private AuthToken getToken(String accessTokenUrl) {
- HttpResponse response = HttpRequest.get(accessTokenUrl).execute();
- JSONObject accessTokenObject = JSONObject.parseObject(response.body());
+ String response = HttpUtil.get(accessTokenUrl);
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
diff --git a/src/main/java/me/zhyd/oauth/request/AuthWeiboRequest.java b/src/main/java/me/zhyd/oauth/request/AuthWeiboRequest.java
index 8b38c8c..ecc3401 100644
--- a/src/main/java/me/zhyd/oauth/request/AuthWeiboRequest.java
+++ b/src/main/java/me/zhyd/oauth/request/AuthWeiboRequest.java
@@ -1,8 +1,8 @@
package me.zhyd.oauth.request;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
+import com.xkcoding.http.support.HttpHeader;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
@@ -36,9 +36,8 @@ public class AuthWeiboRequest extends AuthDefaultRequest {
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
- HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
- String accessTokenStr = response.body();
- JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr);
+ String response = doPostAuthorizationCode(authCallback.getCode());
+ JSONObject accessTokenObject = JSONObject.parseObject(response);
if (accessTokenObject.containsKey("error")) {
throw new AuthException(accessTokenObject.getString("error_description"));
}
@@ -55,11 +54,11 @@ public class AuthWeiboRequest extends AuthDefaultRequest {
String accessToken = authToken.getAccessToken();
String uid = authToken.getUid();
String oauthParam = String.format("uid=%s&access_token=%s", uid, accessToken);
- HttpResponse response = HttpRequest.get(userInfoUrl(authToken))
- .header("Authorization", "OAuth2 " + oauthParam)
- .header("API-RemoteIP", IpUtils.getLocalIp())
- .execute();
- String userInfo = response.body();
+
+ HttpHeader httpHeader = new HttpHeader();
+ httpHeader.add("Authorization", "OAuth2 " + oauthParam);
+ httpHeader.add("API-RemoteIP", IpUtils.getLocalIp());
+ String userInfo = HttpUtil.get(userInfoUrl(authToken), null, httpHeader, false);
JSONObject object = JSONObject.parseObject(userInfo);
if (object.containsKey("error")) {
throw new AuthException(object.getString("error"));
@@ -95,10 +94,13 @@ public class AuthWeiboRequest extends AuthDefaultRequest {
@Override
public AuthResponse revoke(AuthToken authToken) {
- HttpResponse response = doGetRevoke(authToken);
- JSONObject object = JSONObject.parseObject(response.body());
+ String response = doGetRevoke(authToken);
+ JSONObject object = JSONObject.parseObject(response);
if (object.containsKey("error")) {
- return AuthResponse.builder().code(AuthResponseStatus.FAILURE.getCode()).msg(object.getString("error")).build();
+ return AuthResponse.builder()
+ .code(AuthResponseStatus.FAILURE.getCode())
+ .msg(object.getString("error"))
+ .build();
}
// 返回 result = true 表示取消授权成功,否则失败
AuthResponseStatus status = object.getBooleanValue("result") ? AuthResponseStatus.SUCCESS : AuthResponseStatus.FAILURE;
diff --git a/src/main/java/me/zhyd/oauth/utils/AuthChecker.java b/src/main/java/me/zhyd/oauth/utils/AuthChecker.java
index 802098f..178614c 100644
--- a/src/main/java/me/zhyd/oauth/utils/AuthChecker.java
+++ b/src/main/java/me/zhyd/oauth/utils/AuthChecker.java
@@ -47,16 +47,16 @@ public class AuthChecker {
*/
public static void checkConfig(AuthConfig config, AuthSource source) {
String redirectUri = config.getRedirectUri();
- if (!GlobalAuthUtil.isHttpProtocol(redirectUri) && !GlobalAuthUtil.isHttpsProtocol(redirectUri)) {
+ if (!GlobalAuthUtils.isHttpProtocol(redirectUri) && !GlobalAuthUtils.isHttpsProtocol(redirectUri)) {
throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source);
}
// facebook的回调地址必须为https的链接
- if (AuthDefaultSource.FACEBOOK == source && !GlobalAuthUtil.isHttpsProtocol(redirectUri)) {
+ if (AuthDefaultSource.FACEBOOK == source && !GlobalAuthUtils.isHttpsProtocol(redirectUri)) {
// Facebook's redirect uri must use the HTTPS protocol
throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source);
}
// 支付宝在创建回调地址时,不允许使用localhost或者127.0.0.1
- if (AuthDefaultSource.ALIPAY == source && GlobalAuthUtil.isLocalHost(redirectUri)) {
+ if (AuthDefaultSource.ALIPAY == source && GlobalAuthUtils.isLocalHost(redirectUri)) {
// The redirect uri of alipay is forbidden to use localhost or 127.0.0.1
throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source);
}
diff --git a/src/main/java/me/zhyd/oauth/utils/Base64Utils.java b/src/main/java/me/zhyd/oauth/utils/Base64Utils.java
new file mode 100644
index 0000000..a82eaba
--- /dev/null
+++ b/src/main/java/me/zhyd/oauth/utils/Base64Utils.java
@@ -0,0 +1,197 @@
+package me.zhyd.oauth.utils;
+
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * Base64编码
+ *
+ * @author looly
+ * @since 3.2.0
+ */
+public class Base64Utils {
+
+ private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
+ /**
+ * 标准编码表
+ */
+ private static final byte[] STANDARD_ENCODE_TABLE = { //
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //
+ 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', //
+ 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', //
+ 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', //
+ 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', //
+ 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', //
+ 'w', 'x', 'y', 'z', '0', '1', '2', '3', //
+ '4', '5', '6', '7', '8', '9', '+', '/' //
+ };
+ /**
+ * URL安全的编码表,将 + 和 / 替换为 - 和 _
+ */
+ private static final byte[] URL_SAFE_ENCODE_TABLE = { //
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //
+ 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', //
+ 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', //
+ 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', //
+ 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', //
+ 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', //
+ 'w', 'x', 'y', 'z', '0', '1', '2', '3', //
+ '4', '5', '6', '7', '8', '9', '-', '_' //
+ };
+
+ // -------------------------------------------------------------------- encode
+
+ /**
+ * 编码为Base64,非URL安全的
+ *
+ * @param arr 被编码的数组
+ * @param lineSep 在76个char之后是CRLF还是EOF
+ * @return 编码后的bytes
+ */
+ public static byte[] encode(byte[] arr, boolean lineSep) {
+ return encode(arr, lineSep, false);
+ }
+
+ /**
+ * 编码为Base64,URL安全的
+ *
+ * @param arr 被编码的数组
+ * @param lineSep 在76个char之后是CRLF还是EOF
+ * @return 编码后的bytes
+ * @since 3.0.6
+ */
+ public static byte[] encodeUrlSafe(byte[] arr, boolean lineSep) {
+ return encode(arr, lineSep, true);
+ }
+
+ /**
+ * base64编码
+ *
+ * @param source 被编码的base64字符串
+ * @return 被加密后的字符串
+ */
+ public static String encode(CharSequence source) {
+ return encode(source, DEFAULT_CHARSET);
+ }
+
+ /**
+ * base64编码,URL安全
+ *
+ * @param source 被编码的base64字符串
+ * @return 被加密后的字符串
+ * @since 3.0.6
+ */
+ public static String encodeUrlSafe(CharSequence source) {
+ return encodeUrlSafe(source, DEFAULT_CHARSET);
+ }
+
+ /**
+ * base64编码
+ *
+ * @param source 被编码的base64字符串
+ * @param charset 字符集
+ * @return 被加密后的字符串
+ */
+ public static String encode(CharSequence source, Charset charset) {
+ return encode(StringUtils.bytes(source, charset));
+ }
+
+ /**
+ * base64编码,URL安全的
+ *
+ * @param source 被编码的base64字符串
+ * @param charset 字符集
+ * @return 被加密后的字符串
+ * @since 3.0.6
+ */
+ public static String encodeUrlSafe(CharSequence source, Charset charset) {
+ return encodeUrlSafe(StringUtils.bytes(source, charset));
+ }
+
+ /**
+ * base64编码
+ *
+ * @param source 被编码的base64字符串
+ * @return 被加密后的字符串
+ */
+ public static String encode(byte[] source) {
+ return StringUtils.str(encode(source, false), DEFAULT_CHARSET);
+ }
+
+ /**
+ * base64编码,URL安全的
+ *
+ * @param source 被编码的base64字符串
+ * @return 被加密后的字符串
+ * @since 3.0.6
+ */
+ public static String encodeUrlSafe(byte[] source) {
+ return StringUtils.str(encodeUrlSafe(source, false), DEFAULT_CHARSET);
+ }
+
+ /**
+ * 编码为Base64
+ * 如果isMultiLine为true
,则每76个字符一个换行符,否则在一行显示
+ *
+ * @param arr 被编码的数组
+ * @param isMultiLine 在76个char之后是CRLF还是EOF
+ * @param isUrlSafe 是否使用URL安全字符,一般为false
+ * @return 编码后的bytes
+ */
+ public static byte[] encode(byte[] arr, boolean isMultiLine, boolean isUrlSafe) {
+ if (null == arr) {
+ return null;
+ }
+
+ int len = arr.length;
+ if (len == 0) {
+ return new byte[0];
+ }
+
+ int evenlen = (len / 3) * 3;
+ int cnt = ((len - 1) / 3 + 1) << 2;
+ int destlen = cnt + (isMultiLine ? (cnt - 1) / 76 << 1 : 0);
+ byte[] dest = new byte[destlen];
+
+ byte[] encodeTable = isUrlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE;
+
+ for (int s = 0, d = 0, cc = 0; s < evenlen; ) {
+ int i = (arr[s++] & 0xff) << 16 | (arr[s++] & 0xff) << 8 | (arr[s++] & 0xff);
+
+ dest[d++] = encodeTable[(i >>> 18) & 0x3f];
+ dest[d++] = encodeTable[(i >>> 12) & 0x3f];
+ dest[d++] = encodeTable[(i >>> 6) & 0x3f];
+ dest[d++] = encodeTable[i & 0x3f];
+
+ if (isMultiLine && ++cc == 19 && d < destlen - 2) {
+ dest[d++] = '\r';
+ dest[d++] = '\n';
+ cc = 0;
+ }
+ }
+
+ int left = len - evenlen;// 剩余位数
+ if (left > 0) {
+ int i = ((arr[evenlen] & 0xff) << 10) | (left == 2 ? ((arr[len - 1] & 0xff) << 2) : 0);
+
+ dest[destlen - 4] = encodeTable[i >> 12];
+ dest[destlen - 3] = encodeTable[(i >>> 6) & 0x3f];
+
+ if (isUrlSafe) {
+ // 在URL Safe模式下,=为URL中的关键字符,不需要补充。空余的byte位要去掉。
+ int urlSafeLen = destlen - 2;
+ if (2 == left) {
+ dest[destlen - 2] = encodeTable[i & 0x3f];
+ urlSafeLen += 1;
+ }
+ byte[] urlSafeDest = new byte[urlSafeLen];
+ System.arraycopy(dest, 0, urlSafeDest, 0, urlSafeLen);
+ return urlSafeDest;
+ } else {
+ dest[destlen - 2] = (left == 2) ? encodeTable[i & 0x3f] : (byte) '=';
+ dest[destlen - 1] = '=';
+ }
+ }
+ return dest;
+ }
+}
diff --git a/src/main/java/me/zhyd/oauth/utils/GlobalAuthUtil.java b/src/main/java/me/zhyd/oauth/utils/GlobalAuthUtils.java
similarity index 83%
rename from src/main/java/me/zhyd/oauth/utils/GlobalAuthUtil.java
rename to src/main/java/me/zhyd/oauth/utils/GlobalAuthUtils.java
index c6f0db4..5dc883a 100644
--- a/src/main/java/me/zhyd/oauth/utils/GlobalAuthUtil.java
+++ b/src/main/java/me/zhyd/oauth/utils/GlobalAuthUtils.java
@@ -1,9 +1,5 @@
package me.zhyd.oauth.utils;
-import cn.hutool.core.codec.Base64;
-import cn.hutool.core.collection.CollUtil;
-import cn.hutool.core.util.ObjectUtil;
-import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import me.zhyd.oauth.exception.AuthException;
@@ -17,13 +13,7 @@ import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.TreeMap;
+import java.util.*;
/**
* 全局的工具类
@@ -31,7 +21,7 @@ import java.util.TreeMap;
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @since 1.0.0
*/
-public class GlobalAuthUtil {
+public class GlobalAuthUtils {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
private static final String HMAC_SHA1 = "HmacSHA1";
private static final String HMAC_SHA_256 = "HmacSHA256";
@@ -45,7 +35,7 @@ public class GlobalAuthUtil {
*/
public static String generateDingTalkSignature(String secretKey, String timestamp) {
byte[] signData = sign(secretKey.getBytes(DEFAULT_ENCODING), timestamp.getBytes(DEFAULT_ENCODING), HMAC_SHA_256);
- return urlEncode(new String(Base64.encode(signData, false)));
+ return urlEncode(new String(Base64Utils.encode(signData, false)));
}
/**
@@ -79,7 +69,7 @@ public class GlobalAuthUtil {
return "";
}
try {
- String encoded = URLEncoder.encode(value, GlobalAuthUtil.DEFAULT_ENCODING.displayName());
+ String encoded = URLEncoder.encode(value, GlobalAuthUtils.DEFAULT_ENCODING.displayName());
return encoded.replace("+", "%20").replace("*", "%2A").replace("~", "%7E").replace("/", "%2F");
} catch (UnsupportedEncodingException e) {
throw new AuthException("Failed To Encode Uri", e);
@@ -98,7 +88,7 @@ public class GlobalAuthUtil {
return "";
}
try {
- return URLDecoder.decode(value, GlobalAuthUtil.DEFAULT_ENCODING.displayName());
+ return URLDecoder.decode(value, GlobalAuthUtils.DEFAULT_ENCODING.displayName());
} catch (UnsupportedEncodingException e) {
throw new AuthException("Failed To Decode Uri", e);
}
@@ -111,13 +101,13 @@ public class GlobalAuthUtil {
* @return map
*/
public static Map parseStringToMap(String accessTokenStr) {
- Map res = new HashMap<>();
+ Map res = new HashMap<>(6);
if (accessTokenStr.contains("&")) {
String[] fields = accessTokenStr.split("&");
for (String field : fields) {
if (field.contains("=")) {
String[] keyValue = field.split("=");
- res.put(GlobalAuthUtil.urlDecode(keyValue[0]), keyValue.length == 2 ? GlobalAuthUtil.urlDecode(keyValue[1]) : null);
+ res.put(GlobalAuthUtils.urlDecode(keyValue[0]), keyValue.length == 2 ? GlobalAuthUtils.urlDecode(keyValue[1]) : null);
}
}
}
@@ -131,29 +121,16 @@ public class GlobalAuthUtil {
* @param encode 是否转码
* @return str
*/
- public static String parseMapToString(Map params, boolean encode) {
+ public static String parseMapToString(Map params, boolean encode) {
List paramList = new ArrayList<>();
params.forEach((k, v) -> {
- if (ObjectUtil.isNull(v)) {
+ if (null == v) {
paramList.add(k + "=");
} else {
- String valueString = v.toString();
- paramList.add(k + "=" + (encode ? urlEncode(valueString) : valueString));
+ paramList.add(k + "=" + (encode ? urlEncode(v) : v));
}
});
- return CollUtil.join(paramList, "&");
- }
-
- /**
- * 将url的参数列表转换成map
- *
- * @param url 待转换的url
- * @return map
- */
- public static Map parseQueryToMap(String url) {
- Map paramMap = new HashMap<>();
- HttpUtil.decodeParamMap(url, "UTF-8").forEach(paramMap::put);
- return paramMap;
+ return String.join("&", paramList);
}
/**
@@ -230,9 +207,9 @@ public class GlobalAuthUtil {
* @param tokenSecret oauth token secret
* @return BASE64 encoded signature string
*/
- public static String generateTwitterSignature(Map params, String method, String baseUrl, String apiSecret, String tokenSecret) {
- TreeMap map = new TreeMap<>();
- for (Map.Entry e : params.entrySet()) {
+ public static String generateTwitterSignature(Map params, String method, String baseUrl, String apiSecret, String tokenSecret) {
+ TreeMap map = new TreeMap<>();
+ for (Map.Entry e : params.entrySet()) {
map.put(urlEncode(e.getKey()), e.getValue());
}
String str = parseMapToString(map, true);
@@ -240,7 +217,7 @@ public class GlobalAuthUtil {
String signKey = apiSecret + "&" + (StringUtils.isEmpty(tokenSecret) ? "" : tokenSecret);
byte[] signature = sign(signKey.getBytes(DEFAULT_ENCODING), baseStr.getBytes(DEFAULT_ENCODING), HMAC_SHA1);
- return new String(Base64.encode(signature, false));
+ return new String(Base64Utils.encode(signature, false));
}
/**
diff --git a/src/main/java/me/zhyd/oauth/utils/StringUtils.java b/src/main/java/me/zhyd/oauth/utils/StringUtils.java
index b144bdb..4c2d8b8 100644
--- a/src/main/java/me/zhyd/oauth/utils/StringUtils.java
+++ b/src/main/java/me/zhyd/oauth/utils/StringUtils.java
@@ -1,7 +1,6 @@
package me.zhyd.oauth.utils;
-import java.nio.charset.StandardCharsets;
-import java.util.concurrent.ThreadLocalRandom;
+import java.nio.charset.Charset;
/**
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
@@ -36,4 +35,40 @@ public class StringUtils {
return str.concat(appendStr);
}
+ /**
+ * 编码字符串
+ *
+ * @param str 字符串
+ * @param charset 字符集,如果此字段为空,则解码的结果取决于平台
+ * @return 编码后的字节码
+ */
+ public static byte[] bytes(CharSequence str, Charset charset) {
+ if (str == null) {
+ return null;
+ }
+
+ if (null == charset) {
+ return str.toString().getBytes();
+ }
+ return str.toString().getBytes(charset);
+ }
+
+ /**
+ * 解码字节码
+ *
+ * @param data 字符串
+ * @param charset 字符集,如果此字段为空,则解码的结果取决于平台
+ * @return 解码后的字符串
+ */
+ public static String str(byte[] data, Charset charset) {
+ if (data == null) {
+ return null;
+ }
+
+ if (null == charset) {
+ return new String(data);
+ }
+ return new String(data, charset);
+ }
+
}
diff --git a/src/main/java/me/zhyd/oauth/utils/UrlBuilder.java b/src/main/java/me/zhyd/oauth/utils/UrlBuilder.java
index c16ea0c..52e08e1 100644
--- a/src/main/java/me/zhyd/oauth/utils/UrlBuilder.java
+++ b/src/main/java/me/zhyd/oauth/utils/UrlBuilder.java
@@ -1,8 +1,7 @@
package me.zhyd.oauth.utils;
-import cn.hutool.core.lang.Assert;
-import cn.hutool.core.map.MapUtil;
-import cn.hutool.core.util.StrUtil;
+import com.xkcoding.http.util.MapUtil;
+import com.xkcoding.http.util.StringUtil;
import lombok.Setter;
import java.util.LinkedHashMap;
@@ -19,7 +18,7 @@ import java.util.Map;
@Setter
public class UrlBuilder {
- private final Map params = new LinkedHashMap<>(7);
+ private final Map params = new LinkedHashMap<>(7);
private String baseUrl;
private UrlBuilder() {
@@ -44,8 +43,9 @@ public class UrlBuilder {
* @return this UrlBuilder
*/
public UrlBuilder queryParam(String key, Object value) {
- Assert.notBlank(key, "参数名不能为空");
-
+ if (StringUtil.isEmpty(key)) {
+ throw new RuntimeException("参数名不能为空");
+ }
String valueAsString = (value != null ? value.toString() : null);
this.params.put(key, valueAsString);
@@ -72,7 +72,7 @@ public class UrlBuilder {
return this.baseUrl;
}
String baseUrl = StringUtils.appendIfNotContain(this.baseUrl, "?", "&");
- String paramString = GlobalAuthUtil.parseMapToString(this.params, encode);
+ String paramString = MapUtil.parseMapToString(this.params, encode);
return baseUrl + paramString;
}
}
diff --git a/src/test/java/me/zhyd/oauth/sdk/ThirdPartSdkTest.java b/src/test/java/me/zhyd/oauth/sdk/ThirdPartSdkTest.java
index 6aa252c..00aa741 100644
--- a/src/test/java/me/zhyd/oauth/sdk/ThirdPartSdkTest.java
+++ b/src/test/java/me/zhyd/oauth/sdk/ThirdPartSdkTest.java
@@ -1,10 +1,12 @@
package me.zhyd.oauth.sdk;
-import cn.hutool.http.HttpRequest;
-import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
+import com.xkcoding.http.HttpUtil;
import org.junit.Test;
+import java.util.HashMap;
+import java.util.Map;
+
/**
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
@@ -15,26 +17,28 @@ public class ThirdPartSdkTest {
@Test
public void huawei() {
String code = "CF1IwmFc6uZABI9Y795BkhXfvHidIFFw04I4Zc4KML4n+vlXxwNUcQKS4xlopjFDpEk6LzQbjwdTNxvjZ9jqnd/1m5nswhx8X7e0/dL2kyGAMVZWFgVq9ClxNN18b+Z0xtfJjkm7bDnfC3W5h4COgTCoLSjiWKSHWp5hCunp6pQRo1FHovZXm13TLNlhF9mCVtJx3kTQ";
- HttpResponse response = HttpRequest.post("https://oauth-login.cloud.huawei.com/oauth2/v2/token")
- .form("grant_type", "authorization_code")
- .form("code", code)
- .form("client_id", "100994535")
- .form("client_secret", "22aea400bef603fef26d15a79c806eb477b35de0a529758f2a3b1bda32bfb80d")
- .form("redirect_uri", "http://127.0.0.1:8443/oauth/callback/huawei")
- .execute();
- System.out.println(response.body());
+
+ Map form = new HashMap<>(5);
+ form.put("grant_type", "authorization_code");
+ form.put("code", code);
+ form.put("client_id", "100994535");
+ form.put("client_secret", "22aea400bef603fef26d15a79c806eb477b35de0a529758f2a3b1bda32bfb80d");
+ form.put("redirect_uri", "http://127.0.0.1:8443/oauth/callback/huawei");
+
+ String response = HttpUtil.post("https://oauth-login.cloud.huawei.com/oauth2/v2/token", form, false);
+ System.out.println(response);
// {"access_token":"accessToken","expires_in":3600,"refresh_token":"refreshToken","scope":"https:\/\/www.huawei.com\/auth\/account\/base.profile","token_type":"Bearer"}
//
- HttpResponse response2 = HttpRequest.post("https://api.vmall.com/rest.php")
- .form("nsp_ts", System.currentTimeMillis())
- .form("access_token", JSONObject.parseObject(response.body()).getString("access_token"))
- .form("nsp_fmt", "JS")
-// .form("nsp_cb", "_jqjsp")
- .form("nsp_svc", "OpenUP.User.getInfo")
- .execute();
- System.out.println(response2.body());
+ form.clear();
+ form.put("nsp_ts", System.currentTimeMillis() + "");
+ form.put("access_token", JSONObject.parseObject(response).getString("access_token"));
+ form.put("nsp_fmt", "JS");
+ // form.put("nsp_cb", "_jqjsp");
+ form.put("nsp_svc", "OpenUP.User.getInfo");
+ String response2 = HttpUtil.post("https://api.vmall.com/rest.php", form, false);
+ System.out.println(response2);
// 华为性别 0是男,女是1
// {"gender":1,"headPictureURL":"https://upfile-drcn.platform.hicloud.com/FileServer/image/b.0260086000226601572.20190415065228.iBKdTsqaNkdPXSz4N7pIRWAgeu45ec3k.1000.9A5467309F9284B267ECA33B59D3D7DA4A71BC732D3BB24EC6B880A73DEE9BAB.jpg","languageCode":"zh-CN","userID":"260086000226601572","userName":"151****2326","userState":1,"userValidStatus":1}
}
diff --git a/src/test/java/me/zhyd/oauth/utils/GlobalAuthUtilTest.java b/src/test/java/me/zhyd/oauth/utils/GlobalAuthUtilsTest.java
similarity index 72%
rename from src/test/java/me/zhyd/oauth/utils/GlobalAuthUtilTest.java
rename to src/test/java/me/zhyd/oauth/utils/GlobalAuthUtilsTest.java
index ce2a476..243c82a 100644
--- a/src/test/java/me/zhyd/oauth/utils/GlobalAuthUtilTest.java
+++ b/src/test/java/me/zhyd/oauth/utils/GlobalAuthUtilsTest.java
@@ -10,56 +10,54 @@ import java.util.HashMap;
import java.util.Map;
import static me.zhyd.oauth.config.AuthDefaultSource.TWITTER;
-import static me.zhyd.oauth.utils.GlobalAuthUtil.generateTwitterSignature;
-import static me.zhyd.oauth.utils.GlobalAuthUtil.urlEncode;
+import static me.zhyd.oauth.utils.GlobalAuthUtils.generateTwitterSignature;
+import static me.zhyd.oauth.utils.GlobalAuthUtils.urlEncode;
import static org.junit.Assert.assertEquals;
-public class GlobalAuthUtilTest {
+public class GlobalAuthUtilsTest {
@Test
public void testGenerateDingTalkSignature() {
- assertEquals("mLTZEMqIlpAA3xtJ43KcRT0EDLwgSamFe%2FNis5lq9ik%3D",
- GlobalAuthUtil.generateDingTalkSignature("SHA-256", "1562325753000 "));
+ assertEquals("mLTZEMqIlpAA3xtJ43KcRT0EDLwgSamFe%2FNis5lq9ik%3D", GlobalAuthUtils.generateDingTalkSignature("SHA-256", "1562325753000 "));
}
@Test
public void testUrlDecode() {
- assertEquals("", GlobalAuthUtil.urlDecode(null));
- assertEquals("https://www.foo.bar", GlobalAuthUtil.urlDecode("https://www.foo.bar"));
- assertEquals("mLTZEMqIlpAA3xtJ43KcRT0EDLwgSamFe/Nis5lq9ik=",
- GlobalAuthUtil.urlDecode("mLTZEMqIlpAA3xtJ43KcRT0EDLwgSamFe%2FNis5lq9ik%3D"));
+ assertEquals("", GlobalAuthUtils.urlDecode(null));
+ assertEquals("https://www.foo.bar", GlobalAuthUtils.urlDecode("https://www.foo.bar"));
+ assertEquals("mLTZEMqIlpAA3xtJ43KcRT0EDLwgSamFe/Nis5lq9ik=", GlobalAuthUtils.urlDecode("mLTZEMqIlpAA3xtJ43KcRT0EDLwgSamFe%2FNis5lq9ik%3D"));
}
@Test
public void testParseStringToMap() {
Map expected = new HashMap();
expected.put("bar", "baz");
- assertEquals(expected, GlobalAuthUtil.parseStringToMap("foo&bar=baz"));
+ assertEquals(expected, GlobalAuthUtils.parseStringToMap("foo&bar=baz"));
}
@Test
public void testIsHttpProtocol() {
- Assert.assertFalse(GlobalAuthUtil.isHttpProtocol(""));
- Assert.assertFalse(GlobalAuthUtil.isHttpProtocol("foo"));
+ Assert.assertFalse(GlobalAuthUtils.isHttpProtocol(""));
+ Assert.assertFalse(GlobalAuthUtils.isHttpProtocol("foo"));
- Assert.assertTrue(GlobalAuthUtil.isHttpProtocol("http://www.foo.bar"));
+ Assert.assertTrue(GlobalAuthUtils.isHttpProtocol("http://www.foo.bar"));
}
@Test
public void testIsHttpsProtocol() {
- Assert.assertFalse(GlobalAuthUtil.isHttpsProtocol(""));
- Assert.assertFalse(GlobalAuthUtil.isHttpsProtocol("foo"));
+ Assert.assertFalse(GlobalAuthUtils.isHttpsProtocol(""));
+ Assert.assertFalse(GlobalAuthUtils.isHttpsProtocol("foo"));
- Assert.assertTrue(GlobalAuthUtil.isHttpsProtocol("https://www.foo.bar"));
+ Assert.assertTrue(GlobalAuthUtils.isHttpsProtocol("https://www.foo.bar"));
}
@Test
public void testIsLocalHost() {
- Assert.assertFalse(GlobalAuthUtil.isLocalHost("foo"));
+ Assert.assertFalse(GlobalAuthUtils.isLocalHost("foo"));
- Assert.assertTrue(GlobalAuthUtil.isLocalHost(""));
- Assert.assertTrue(GlobalAuthUtil.isLocalHost("127.0.0.1"));
- Assert.assertTrue(GlobalAuthUtil.isLocalHost("localhost"));
+ Assert.assertTrue(GlobalAuthUtils.isLocalHost(""));
+ Assert.assertTrue(GlobalAuthUtils.isLocalHost("127.0.0.1"));
+ Assert.assertTrue(GlobalAuthUtils.isLocalHost("localhost"));
}
@Test
@@ -69,7 +67,7 @@ public class GlobalAuthUtilTest {
.clientSecret("0YX3RH2DnPiT77pgzLzFdfpMKX8ENLIWQKYQ7lG5TERuZNgXN5")
.redirectUri("https://codinglife.tech")
.build();
- Map params = new HashMap<>();
+ Map params = new HashMap<>();
params.put("oauth_consumer_key", config.getClientId());
params.put("oauth_nonce", "sTj7Ivg73u052eXstpoS1AWQCynuDEPN");
params.put("oauth_signature_method", "HMAC-SHA1");
@@ -81,7 +79,7 @@ public class GlobalAuthUtilTest {
params.put("oauth_signature", generateTwitterSignature(params, "POST", baseUrl, config.getClientSecret(), null));
params.forEach((k, v) -> params.put(k, "\"" + urlEncode(v.toString()) + "\""));
- String actual = "OAuth " + GlobalAuthUtil.parseMapToString(params, false).replaceAll("&", ", ");
+ String actual = "OAuth " + GlobalAuthUtils.parseMapToString(params, false).replaceAll("&", ", ");
assertEquals("OAuth oauth_nonce=\"sTj7Ivg73u052eXstpoS1AWQCynuDEPN\", oauth_signature=\"%2BL5Jq%2FTaKubge04cWw%2B4yfjFlaU%3D\", oauth_callback=\"https%3A%2F%2Fcodinglife.tech\", oauth_consumer_key=\"HD0XLqzi5Wz0G08rh45Cg8mgh\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1569750981\", oauth_version=\"1.0\"", actual);
}
@@ -96,7 +94,7 @@ public class GlobalAuthUtilTest {
.oauthToken("W_KLmAAAAAAAxq5LAAABbXxJeD0")
.oauthVerifier("lYou4gxfA6S5KioUa8VF8HCShzA2nSxp")
.build();
- Map params = new HashMap<>();
+ Map params = new HashMap<>();
params.put("oauth_consumer_key", config.getClientId());
params.put("oauth_nonce", "sTj7Ivg73u052eXstpoS1AWQCynuDEPN");
params.put("oauth_signature_method", "HMAC-SHA1");
@@ -105,10 +103,11 @@ public class GlobalAuthUtilTest {
params.put("oauth_verifier", authCallback.getOauthVerifier());
params.put("oauth_version", "1.0");
- params.put("oauth_signature", generateTwitterSignature(params, "POST", TWITTER.accessToken(), config.getClientSecret(), authCallback.getOauthToken()));
+ params.put("oauth_signature", generateTwitterSignature(params, "POST", TWITTER.accessToken(), config.getClientSecret(), authCallback
+ .getOauthToken()));
params.forEach((k, v) -> params.put(k, "\"" + urlEncode(v.toString()) + "\""));
- String actual = "OAuth " + GlobalAuthUtil.parseMapToString(params, false).replaceAll("&", ", ");
+ String actual = "OAuth " + GlobalAuthUtils.parseMapToString(params, false).replaceAll("&", ", ");
assertEquals("OAuth oauth_verifier=\"lYou4gxfA6S5KioUa8VF8HCShzA2nSxp\", oauth_nonce=\"sTj7Ivg73u052eXstpoS1AWQCynuDEPN\", oauth_signature=\"9i0lmWgvphtkl2KcCO9VyZ3K2%2F0%3D\", oauth_token=\"W_KLmAAAAAAAxq5LAAABbXxJeD0\", oauth_consumer_key=\"HD0XLqzi5Wz0G08rh45Cg8mgh\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1569751082\", oauth_version=\"1.0\"", actual);
}
@@ -126,7 +125,7 @@ public class GlobalAuthUtilTest {
.screenName("pengisgood")
.build();
- Map oauthParams = new HashMap<>();
+ Map oauthParams = new HashMap<>();
oauthParams.put("oauth_consumer_key", config.getClientId());
oauthParams.put("oauth_nonce", "sTj7Ivg73u052eXstpoS1AWQCynuDEPN");
oauthParams.put("oauth_signature_method", "HMAC-SHA1");
@@ -134,17 +133,17 @@ public class GlobalAuthUtilTest {
oauthParams.put("oauth_token", authToken.getOauthToken());
oauthParams.put("oauth_version", "1.0");
- Map queryParams = new HashMap<>();
+ Map queryParams = new HashMap<>();
queryParams.put("user_id", authToken.getUserId());
queryParams.put("screen_name", authToken.getScreenName());
- queryParams.put("include_entities", true);
+ queryParams.put("include_entities", Boolean.toString(true));
- Map params = new HashMap<>(oauthParams);
- params.putAll(queryParams);
- oauthParams.put("oauth_signature", generateTwitterSignature(params, "GET", TWITTER.userInfo(), config.getClientSecret(), authToken.getOauthTokenSecret()));
+ Map params = new HashMap<>(queryParams);
+ oauthParams.put("oauth_signature", generateTwitterSignature(params, "GET", TWITTER.userInfo(), config.getClientSecret(), authToken
+ .getOauthTokenSecret()));
oauthParams.forEach((k, v) -> oauthParams.put(k, "\"" + urlEncode(v.toString()) + "\""));
- String actual = "OAuth "+ GlobalAuthUtil.parseMapToString(oauthParams, false).replaceAll("&", ", ");
+ String actual = "OAuth " + GlobalAuthUtils.parseMapToString(oauthParams, false).replaceAll("&", ", ");
assertEquals("OAuth oauth_nonce=\"sTj7Ivg73u052eXstpoS1AWQCynuDEPN\", oauth_signature=\"elV04U%2FiLm%2Ff3ue1dSrZeChFkEM%3D\", oauth_token=\"1961977975-PcFQaCnpN9h9xqtqHwHlpGBXFrHJ9bOLy7OtGAL\", oauth_consumer_key=\"HD0XLqzi5Wz0G08rh45Cg8mgh\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1569751082\", oauth_version=\"1.0\"", actual);
}
}
--
GitLab