一.先加入需要的配置文件和依赖以及用到的工具类
1.在application.yml中加入配置文件

wx:open:# 微信开放平台 appidapp_id: wxed9954c01bb89b47# 微信开放平台 appsecretapp_secret: a7482517235173ddb4083788de60b90e# 微信开放平台 重定向url(guli.shop需要在微信开放平台配置)redirect_url: http://guli.shop/api/ucenter/wx/callback

2.在pom中加入需要的依赖文件

 <!--httpclient--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.1</version></dependency><!--commons-io--><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version></dependency><!--gson--><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.2</version></dependency><!-- JWT --><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.7.0</version></dependency>入代码片

3.在包下加入需要用到的工具类 需要用到两个工具类 HttpClientUtils 和 JwtUtils

package com.atguigu.utils;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;/***  依赖的jar包有:commons-lang-2.6.jar、httpclient-4.3.2.jar、httpcore-4.3.1.jar、commons-io-2.4.jar* @author zhaoyb**/
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<String, String> params) throws ConnectTimeoutException,SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);}public static String postParameters(String url, Map<String, String> 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);}/*** 发送一个 Post 请求, 使用指定的字符集编码.** @param url* @param body RequestBody* @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3* @param charset 编码* @param connTimeout 建立链接超时时间,毫秒.* @param readTimeout 响应超时时间,毫秒.* @return ResponseBody, 使用指定的字符集编码.* @throws ConnectTimeoutException 建立链接超时异常* @throws SocketTimeoutException  响应超时* @throws Exception*/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;}/*** 提交form表单** @param url* @param params* @param connTimeout* @param readTimeout* @return* @throws ConnectTimeoutException* @throws SocketTimeoutException* @throws Exception*/public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);try {if (params != null && !params.isEmpty()) {List<NameValuePair> formParams = new ArrayList<NameValuePair>();Set<Entry<String, String>> entrySet = params.entrySet();for (Entry<String, String> 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<String, String> 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();}}}/*** 发送一个 GET 请求** @param url* @param charset* @param connTimeout  建立链接超时时间,毫秒.* @param readTimeout  响应超时时间,毫秒.* @return* @throws ConnectTimeoutException   建立链接超时* @throws SocketTimeoutException   响应超时* @throws Exception*/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;}/*** 从 response 里获取 charset** @param ressponse* @return*/@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;}/*** 创建 SSL连接* @return* @throws GeneralSecurityException*/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");/*Map<String,String> map = new HashMap<String,String>();map.put("name", "111");map.put("page", "222");String str= postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/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();}}}

4.加入另一个工具类 JwtUtils

package com.atguigu.utils;import com.atguigu.entity.MemberCenter;
import org.springframework.util.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;import java.util.Date;public class JwtUtils {public static final String SUBJECT = "guli";//秘钥public static final String APPSECRET = "guli";public static final long EXPIRE = 1000 * 60 * 30;  //过期时间,毫秒,30分钟/*** 根据对象生成jwt的token字符串*/public static String geneJsonWebToken(MemberCenter member) {if (member == null || StringUtils.isEmpty(member.getId())|| StringUtils.isEmpty(member.getNickname())|| StringUtils.isEmpty(member.getAvatar())) {return null;}String token = Jwts.builder().setSubject(SUBJECT).claim("id", member.getId()).claim("nickname", member.getNickname()).claim("avatar", member.getAvatar()).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + EXPIRE)).signWith(SignatureAlgorithm.HS256, APPSECRET).compact();return token;}/*** 校验jwt token*/public static Claims checkJWT(String token) {Claims claims = Jwts.parser().setSigningKey(APPSECRET).parseClaimsJws(token).getBody();return claims;}}

5.代码实现在java微信二维码后台登陆实现 ( 二 )

java微信二维码第三方后台登陆实现 ( 一 )相关推荐

  1. java微信二维码登录

    1.注册 微信开放平台:https://open.weixin.qq.com 2.邮箱激活 3.完善开发者资料 4.开发者资质认证 准备营业执照,1-2个工作日审批.300元 5.创建网站应用 提交审 ...

  2. Java支付宝二维码支付和退款,微信二维码支付

    在蚂蚁金服开发平台下载demo 打开 TradePayDemo 项目,里面的main可以直接运行,在配置文件zfbinfo.properties中改为自己支付宝的信息 # 支付宝网关名.partner ...

  3. Java如何解析个人或他人微信二维码内的信息

    这两天对微信二维码比较感兴趣,所以就花了点时间学习了一下,下面我将先介绍一下如何解析微信二维码内的信息. 直接上代码: import java.awt.image.BufferedImage; imp ...

  4. opencv微信二维码引擎的使用(for java)

    前面讲了windows系统下opencv+opencv的编译方法,编译方法和编译好的文件如下: Windows下联合编译opencv+opencv_contrib微信二维码引擎 OpenCV4.5.2 ...

  5. 魔坊APP项目-15-邀请好友(业务逻辑流程图、服务端提供邀请好友的二维码生成接口、客户端通过第三方识别微信二维码,服务端提供接口允许访问、App配置私有协议,允许第三方应用通过私有协议,唤醒APP)

    邀请好友 1.业务逻辑流程图 客户端提供点击"邀请好友"以后的页面frame,html/invite.html,代码: <!DOCTYPE html> <html ...

  6. Java如何获取微信二维码内的信息

    import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.i ...

  7. 微信二维码的生成(java后端)--邀请新人

    目录 写在前言 1.微信官方文档 2.具体分析 写在前言 最近因为在学习微信小程序邀请新用户的功能,所以需要后端生成二维码并且携带本人的用户id或者其他的信息,传给前端.用户通过这个二维码去进行登录或 ...

  8. Day212.OAuth2、微信二维码登入注册功能、用户登录信息前后端供、讲师列表前后端 -谷粒学院

    谷粒学院 OAuth2的使用场景 一.OAuth2解决什么问题 1.OAuth2提出的背景 照片拥有者想要在云冲印服务上打印照片,云冲印服务需要访问云存储服务上的资源 2.图例 资源拥有者:照片拥有者 ...

  9. 开放平台–扫描微信二维码登录

    准备 如不了解第三方登录流程,建议先大概了解一下,在来看看代码. 说明: 由于开放平台无测试号测试,所以只能上开放平台进行配置信息.公众平台的测试号并不能给开放平台使用. 微信开放平台地址:https ...

最新文章

  1. AJAX ControlToolkit学习日志-ModalPopupExtender(16)
  2. 再也不怕复现论文!arXiv携手Papers with Code,提交论文+上传代码一步到位
  3. 二十三种设计模式-六大原则
  4. unlink与close关系
  5. bzoj:3110: [Zjoi2013]K大数查询
  6. linux文件内容添加序号,nl命令将指定的各个文件添加行号编号序号标注后写到标准输出...
  7. GDUFE ACM-1045
  8. 编程模式如何结束未响应的程序
  9. Spark 调用 hive使用动态分区插入数据
  10. 程序员找工作防止小破公司的画饼充饥方法
  11. UE4移动平台上基于物理的着色
  12. fifa15服务器位置,《FIFA 15》系统菜单界面图文详解 各游戏模式详解
  13. 通过存储过程,插入300万条数据的一点思考?
  14. 网易和淘宝的rem方案剖析
  15. KEmulator 屏蔽内存查看器功能
  16. 我的世界服务器无限背包,我的世界 无限背包MOD 我的世界1.7无限背包MOD
  17. 斯坦福课程Knowledge Graphs-What is a Knowledge Graph?
  18. 【 直接复制不用下载 】-- 走遍美国总词汇(完整版)
  19. Python初学者之路--range函数、切片、if-elif语句
  20. sgm3157功能_SGM3157

热门文章

  1. 网站流量提升-网站推广方法大全
  2. (转载博客园~雨落忧伤~)iis 设置了主机名 就不能访问
  3. P8-Windows与网络基础-Windows基本命令-目录文件操作(cd、dir、md、rd、move、copy、xcopy、del)
  4. 杭电ACM1218——Blurred Vision
  5. 英文有声读物网站(转贴)
  6. 经纬度的semicircle单位
  7. 纯白的月光石(《月光石》中文版)
  8. Java中的高级“过滤器“Stream流
  9. asp.net core程序集自动注入
  10. PON为什么被称为无源光网络?不同PON技术的主要区别是什么?