环境
<!--使用HttpUtils需要的依赖-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.12</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
<scope>compile</scope>
</dependency>
package com.xc.common.utils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
package com.xc.common.exception;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.util.List;
@Slf4j
public class Assert {
/**
* 断言对象不为空,为空则抛异常
*
* @param obj
* @param BizCodeEnume
*/
public static void notNull(Object obj, BizCodeEnume BizCodeEnume) {
if (obj == null) {
// log.info("obj is null...............................");
System.out.println("obj is null...............................");
throw new BusinessException(BizCodeEnume);
}
}
/**
* 断言对象为空
* 如果对象obj不为空,则抛出异常
*
* @param object
* @param BizCodeEnume
*/
public static void isNull(Object object, BizCodeEnume BizCodeEnume) {
if (object != null) {
// log.info("obj is not null......");
System.out.println("obj is not null......");
throw new BusinessException(BizCodeEnume);
}
}
/**
* 断言集合为空
* 如果集合不为空,则抛出异常
*
* @param list
* @param BizCodeEnume
*/
public static void isNullList(List list, BizCodeEnume BizCodeEnume) {
if (CollectionUtils.isNotEmpty(list)) {
// log.info("list is not null......");
System.out.println("list is not null......");
throw new BusinessException(BizCodeEnume);
}
}
/**
* 断言集合不为空
* 如果集合为空,则抛出异常
*
* @param list
* @param BizCodeEnume
*/
public static void notEmptyList(List list, BizCodeEnume BizCodeEnume) {
if (CollectionUtils.isEmpty(list)) {
// log.info("list is null......");
System.out.println("list is null......");
throw new BusinessException(BizCodeEnume);
}
}
/**
* 断言表达式为真
* 如果不为真,则抛出异常
*
* @param expression 是否成功
*/
public static void isTrue(boolean expression, BizCodeEnume BizCodeEnume) {
if (!expression) {
// log.info("fail...............");
System.out.println("fail...............");
throw new BusinessException(BizCodeEnume);
}
}
/**
* 断言两个对象不相等
* 如果相等,则抛出异常
*
* @param m1
* @param m2
* @param BizCodeEnume
*/
public static void notEquals(Object m1, Object m2, BizCodeEnume BizCodeEnume) {
if (m1.equals(m2)) {
// log.info("equals...............");
System.out.println("equals...............");
throw new BusinessException(BizCodeEnume);
}
}
/**
* 断言两个对象相等
* 如果不相等,则抛出异常
*
* @param m1
* @param m2
* @param BizCodeEnume
*/
public static void equals(Object m1, Object m2, BizCodeEnume BizCodeEnume) {
if (!m1.equals(m2)) {
// log.info("not equals...............");
System.out.println("not equals...............");
throw new BusinessException(BizCodeEnume);
}
}
/**
* 断言参数不为空
* 如果为空,则抛出异常
*
* @param s
* @param BizCodeEnume
*/
public static void notEmpty(String s, BizCodeEnume BizCodeEnume) {
if (StringUtils.isEmpty(s)) {
// log.info("is empty...............");
System.out.println("is empty...............");
throw new BusinessException(BizCodeEnume);
}
}
}
后端实现
实体
/** * 社交用户的唯一id */ private String socialUid; /** * 访问令牌 */ private String accessToken; /** * 访问令牌的时间 */ private String expiresIn;/** * 昵称 */ private String nickname;
//Controller @PostMapping("/oauth2/gitee-login") public R giteeLogin(@RequestParam("giteeInfo") String giteeInfo) throws Exception { MemberEntity member = memberService.giteeLogin(giteeInfo); return R.ok().setData(member); }//Service
MemberEntity giteeLogin(String giteeInfo) throws Exception;//ServiceImpl
public MemberEntity giteeLogin(String giteeInfo) throws Exception { // 拿到accesstoken,获取用户基本信息 JSONObject baseJson = JSON.parseObject(giteeInfo); Map<String, String> params = new HashMap<>(); String accessToken = baseJson.getString("access_token"); String expiresIn = baseJson.getString("expires_in"); params.put("access_token", accessToken); HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", null, params); Assert.isTrue(response.getStatusLine().getStatusCode() == 200, BizCodeEnume.OAUTH2_GITEE_EXCEPTION); String s = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = JSON.parseObject(s); String id = jsonObject.getString("id"); MemberEntity member = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", "gitee" + "_" + id)); if (member != null) { // 说明已经注册过,更新令牌、令牌过期时间 MemberEntity newMember = new MemberEntity(); newMember.setId(member.getId()); newMember.setAccessToken(accessToken); newMember.setExpiresIn(expiresIn); this.updateById(member); return member; } else { // 第一次登录,需要注册 MemberEntity newMember = new MemberEntity(); newMember.setSocialUid("gitee" + "_" + id); newMember.setNickname(jsonObject.getString("name"));//用户名字 newMember.setAccessToken(accessToken); newMember.setExpiresIn(expiresIn); this.save(newMember); return newMember; } }
前端事件
<li>
<!--需要注意client_id=是gitee中申请的第三方应用,id都是唯一的-->
<a href="https://gitee.com/oauth/authorize?client_id=11340ee4
&redirect_uri=http://xc.com/web/oauth2/gitee/success&response_type=code">
<img style="width: 18px;height: 18px;" src="/static/login/JD_img/gitee.png"/>
<span>gitee</span>
</a>
</li>
后端响应前端事件并保存用户数据
package com.xc.gulimallauthserver.controller; import com.xc.common.utils.HttpUtils; import com.xc.common.utils.R; import com.xc.gulimallauthserver.feign.MemberFeignservice; import org.apache.http.HttpResponse; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/web/oauth2") public class OAuth2Controller { @Resource private MemberFeignservice memberFeignService; /** * 社交登录成功回调 * @param code * @return * @throws Exception */ @GetMapping("/gitee/success") public String gitee(@RequestParam("code") String code) throws Exception { // 准备请求参数 Map<String,String> params = new HashMap<>(); params.put("client_id","11340ee43");//gitee申请第三方应用 params.put("redirect_uri","http://xc.com/web/oauth2/gitee/success"); params.put("client_secret","7ebef6");//gitee申请第三方应用 params.put("code",code); params.put("grant_type","authorization_code"); // 获取accesstoken HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", null, null, params); if (response.getStatusLine().getStatusCode() == 200) { // 说明获取到了 // 取出返回数据 String giteeInfo = EntityUtils.toString(response.getEntity()); // 我这里使用了远程调用,接口就是上面的giteeLogin R r = memberFeignService.giteeLogin(giteeInfo); if (r.getCode() == 0) { return "redirect:http://xc.com/"; } }else{ return "redirect:http://xc.com/login.html"; } return "redirect:http://xc.com/login.html"; } }
gitee申请第三方应用
然后申请就好了
这里的redirect_uri路径要与前端事件以及OAuth2Controller里的redirect_uri保存一致