微服务token错误失效

问题无法获取小程序二维码?

我的问题:wxAccessToken接口用于token刷新,40分钟一次没有问题,但是如果项目关闭40分钟以上,定时任务就废掉了,两种解决方式

	还有其他方式请大佬们留言学习学习,谢谢

1,主动调用那个接口刷新接口

2、等待40分钟,等待定时任务自己执

生成二维码:测试工具:获取appid,appsecret,利用工具:
https://mp.weixin.qq.com/debug/

自己定义的token是直接在微信官网中获取token

微服务token错误失效_第1张图片

获取图片的接口,其中加了流。微信小程序

微服务token错误失效_第2张图片

唯一标识,和秘钥在自己的公司开发公众号平台上查看

微服务token错误失效_第3张图片

获取token 工具类

package com.zfbgt.complaint.api.sso.utils;
import lombok.extern.slf4j.Slf4j;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Slf4j
public class UrlUtil {

    private final Logger LOG = LogManager.getLogger(this.getClass());


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @param
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, Map<String, ?> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        String param = "";
        Iterator<String> it = paramMap.keySet().iterator();

        while (it.hasNext()) {
            String key = it.next();
            param += key + "=" + paramMap.get(key) + "&";
        }

        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doPost(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, (String) param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static HttpEntity PostRow(String token,String path) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="
                + token;
        String json = "{\"path\":\""+path+"\"}";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity postingString = new StringEntity(json);// json传递
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        return response.getEntity();

    }
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static HttpEntity PostCircular(String token,String path,String usrId) throws IOException {
        log.info("PostCircular请求值:[{}]...[{}]..",path,usrId);
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="
                + token;
        //  String json = "{\"path\":\""+path+"\"}";
        String json = "{\n" +
                " \"path\":\""+path+"\",\n" +
                " \"scene\":\""+usrId+"\",\n" +
                " \"is_hyaline\":true,\n" +
                "\"line_color\": {\"r\":255,\"g\":255,\"b\":255}\n" +
                "}";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity postingString = new StringEntity(json);// json传递
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        return response.getEntity();

    }

    public static HttpEntity whitePostCircular(String token,String path,String usrId) throws IOException {
        log.info("whitePostCircular请求值:[{}]...[{}]..",path,usrId);//打印日志
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="
                + token;
        //  String json = "{\"path\":\""+path+"\"}";
        String json = "{\n" +
                " \"path\":\""+path+"\",\n" +
                " \"scene\":\""+usrId+"\",\n" +
                " \"is_hyaline\":true,\n" +
                "\"line_color\": {\"r\":255,\"g\":255,\"b\":255}\n" +
                "}";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity postingString = new StringEntity(json);// json传递
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        return response.getEntity();

    }

    public static HttpEntity newsPostCircular(String token,String path) throws IOException {
        String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token="
                + token;
        //  String json = "{\"path\":\""+path+"\"}";
        String json = "{\n" +
                " \"path\":\""+path+"\",\n" +
                " \"is_hyaline\":true,\n" +
                "\"line_color\": {\"r\":255,\"g\":255,\"b\":255}\n" +
                "}";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity postingString = new StringEntity(json);// json传递
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        return response.getEntity();

    }
}
// 每个角色对应的名性片
@NotLogin
@RequestMapping("/usrinfo/access")
public void usrInfoAccess(String path, HttpServletResponse response, String usrId) {
    try {
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "填写获取token值");
        map.put("appid", "唯一标识");
        map.put("secret", "微信小程序秘钥");
        String accessToken =getToken();//调用上面弄的token方法
        // 判断的没参数
        if (StringUtils.isEmpty(usrId)) {
            usrId = null;
        } else {
            // 1、我套系统的返回值很有问题,所有的错误返回值全是400,前端根本没法判断,做逻辑处理。
            // 2、我就在这里可以使用参数校验,一般这种接口us人ID不合法根本进不来方法
            // response里面返回json
            //判断长度小于5或等于5
            if (usrId.length()<=5){
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(objectMapper.writeValueAsString(new DTO(400,"usrId长度过		短",null)));
                response.setStatus(HttpStatus.OK.value());
            }
            usrId = usrId.substring(5, usrId.length());
        }
        log.info("usrId长度为:[{}]",usrId);//打印日志
        HttpEntity httpEntity = UrlUtil.whitePostCircular(accessToken, path, usrId);
        InputStream content = httpEntity.getContent();
        BufferedInputStream fis = new BufferedInputStream(content);
        response.setContentType("image/jpg");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        //定义个数组,由于读取缓冲流中的内容
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fis.read(buffer)) != -1) {//读取流
            toClient.write(buffer, 0, bytesRead);
        }
        toClient.flush();
        toClient.close();
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

你可能感兴趣的:(微服务,microservices,架构)