目录
依赖工具类关键代码(以gitee为例)==还不理解的去看 [官方文档](https://gitee.com/api/v5/oauth_doc#/)== 依赖
org.projectlombok lombok org.apache.httpcomponents httpclient 4.5.6 com.alibaba fastjson 1.2.51 commons-io commons-io 2.6 commons-lang commons-lang 2.6 com.google.code.gson gson 2.8.5
工具类
package com.ljh; import org.apache.commons.io.IOUtils;import org.apache.commons.lang.StringUtils;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NamevaluePair;import org.apache.http.client.HttpClient;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.config.RequestConfig.Builder;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.ConnectTimeoutException;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.SSLContextBuilder;import org.apache.http.conn.ssl.TrustStrategy;import org.apache.http.conn.ssl.X509HostnameVerifier;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNamevaluePair; import javax.net.ssl.SSLContext;import javax.net.ssl.SSLException;import javax.net.ssl.SSLSession;import javax.net.ssl.SSLSocket;import java.io.IOException;import java.net.SocketTimeoutException;import java.security.GeneralSecurityException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set; public class HttpClientUtils { public static final int connTimeout=10000;public static final int readTimeout=10000;public static final String charset="UTF-8";private static HttpClient client = null; static {PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(128);cm.setDefaultMaxPerRoute(128);client = HttpClients.custom().setConnectionManager(cm).build();} public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);} public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);} public static String postParameters(String url, Map params) throws ConnectTimeoutException,SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);} public static String postParameters(String url, Map params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);} public static String get(String url) throws Exception {return get(url, charset, null, null);} public static String get(String url, String charset) throws Exception {return get(url, charset, connTimeout, readTimeout);} public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)throws ConnectTimeoutException, SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);String result = "";try {if (StringUtils.isNotBlank(body)) {HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));post.setEntity(entity);}// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build()); HttpResponse res;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(post);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(post);}result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {post.releaseConnection();if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;} public static String postForm(String url, Map params, Map headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,SocketTimeoutException, Exception { HttpClient client = null;HttpPost post = new HttpPost(url);try {if (params != null && !params.isEmpty()) {List formParams = new ArrayList();Set> entrySet = params.entrySet();for (Entry entry : entrySet) {formParams.add(new BasicNamevaluePair(entry.getKey(), entry.getValue()));}UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);post.setEntity(entity);} if (headers != null && !headers.isEmpty()) {for (Entry entry : headers.entrySet()) {post.addHeader(entry.getKey(), entry.getValue());}}// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build());HttpResponse res = null;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(post);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(post);}return IOUtils.toString(res.getEntity().getContent(), "UTF-8");} finally {post.releaseConnection();if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}} public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)throws ConnectTimeoutException,SocketTimeoutException, Exception { HttpClient client = null;HttpGet get = new HttpGet(url);String result = "";try {// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}get.setConfig(customReqConf.build()); HttpResponse res = null; if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(get);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(get);} result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {get.releaseConnection();if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;} @SuppressWarnings("unused")private static String getCharsetFromResponse(HttpResponse ressponse) {// Content-Type:text/html; charset=GBKif (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {String contentType = ressponse.getEntity().getContentType().getValue();if (contentType.contains("charset=")) {return contentType.substring(contentType.indexOf("charset=") + 8);}}return null;} private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {return true;}}).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;} @Overridepublic void verify(String host, SSLSocket ssl)throws IOException {} @Overridepublic void verify(String host, X509Certificate cert)throws SSLException {} @Overridepublic void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {} }); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (GeneralSecurityException e) {throw e;}} public static void main(String[] args) {try {String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);//String str= get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK"); System.out.println(str);} catch (ConnectTimeoutException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SocketTimeoutException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}} }
关键代码(以gitee为例)
package com.ljh.controller;import com.google.gson.Gson;import com.ljh.HttpClientUtils;import lombok.extern.slf4j.Slf4j;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.ResponseBody;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;@Controller@Slf4jpublic class TestController { @GetMapping public String login(){ return "redirect:https://gitee.com/oauth/authorize?client_id=1cc53d5bffa15f75e8633e2213481554a6f7e1ed52e47f0dcdeee6d04b2ecc57&redirect_uri=http://106.14.223.42:8084/callback&response_type=code"; } @RequestMapping("/callback") @ResponseBody public String callback(String code) throws Exception { //由于确定登陆会回调该方法且携带一个code在地址栏,我们可以通过参数的方式获取 //或者使用HttpServletRequest注入的方式去获取 log.info("进入回调"); log.info("获取code{}",code); //获取令牌参数 String body="grant_type=authorization_code&code="+code+ "&client_id=1cc53d5bffa15f75e8633e2213481554a6f7e1ed52e47f0dcdeee6d04b2ecc57"+ "&redirect_uri=http://106.14.223.42:8084/callback"+ "&client_secret=2cd54587fc60ccd9447c905e523601aff11a056b02c324042a1ab300d17bbe94"; log.info("发送获取令牌请求"); String s=""; try { s = HttpClientUtils.post("https://gitee.com/oauth/token",body,"application/x-www-form-urlencoded","utf-8",30000,30000); } catch (Exception e) { log.error("获取令牌失败{}",e.getMessage()); } log.info("获取令牌请求的返回值{}",s); //这里需要注意一下,发送的是post请求,第三个参数mimeType,我使用的是application/x-www-form-urlencoded,数据按照 key1=val1&key2=val2 的方式进行编码,key 和 val 都进行了 URL 转码,数据放在body里 //使用gson的方式去解析返回的内容 Gson gson = new Gson(); HashMap hashMap = gson.fromJson(s, HashMap.class); String access_token = (String)hashMap.get("access_token"); log.info("令牌:{}",access_token); System.out.println(s); //获取用户信息需要携带token就可以了,其他第三方登陆可能需要携带用户id,主要看文档 log.info("获取用户信息"); String s2 = HttpClientUtils.get("https://gitee.com/api/v5/user?access_token=" + access_token); log.info("用户信息{}",s2); return s2; }}
还不理解的去看 官方文档