springboot通过过滤器实现将部分请求处理后转发到第三方平台

前言

这几天在搞一个项目,主要是将部分请求进行请求转发到第三方平台。主要是两个操作。请求转发和第三方请求。

过滤器

自定义过滤器 ReqResFilter 必须实现 javax.servlet.Filter
然后添加注解 @WebFilter(javax.servlet.annotation.WebFilter),urlPatterns 过滤器要过滤的URL规则配置,filterName 过滤器的名称。

请求转发

request.getRequestDispatcher(newUri).forward(request,response);

http3

OkHttpClient

OkHttpClient.Builder OBuilder = new OkHttpClient().newBuilder()
		.connectTimeout(10000L, TimeUnit.SECONDS)  // 最大连接时间
		.readTimeout(10000L, TimeUnit.SECONDS)     // 最大读取时间
		.writeTimeout(10000L, TimeUnit.SECONDS);   // 最大写入时间
if (targetUrl.startsWith("https")) {
	// 添加SSL证书信任     【SSLSocketClient】
	builder = builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager());
}
OkHttpClient client = builder.build();

Request

// POST
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, data);
Request.Builder rBudlder= new Request.Builder().url(url).post(body);
// GET
String urlParameter = request.getQueryString();//网址中的参数
Request.Builder rBudlder= new Request.Builder().url(url + "?" + urlParameter).method("GET", null);
// 其他
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, data);
Request.Builder rBudlder= new Request.Builder().url(url).method(request.getMethod(), body);
// 设置来源 [可忽略]
rBudlder.addHeader("Origin", "https://XXX");
rBudlder.addHeader("Referer", "https://XXX/XX");
Request request = rBudlder.build();

Response

Request req = rBudlder.build();
Response resp = client.newCall(req).execute();

请求

String res = resp.body().string();

参考代码

@Slf4j
@Component
@WebFilter(filterName = "reqFilter", urlPatterns = "/*")
public class ReqForwardFilter implements Filter {
    @Autowired
    private SmartHomeConfigService smartHomeConfigService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //可能需要请求转发到新的地址
        boolean next = handllerReq(req, resp);
        if (next) {
            chain.doFilter(req, resp);//交给下一个过滤器或servlet处理
        }
    }
    @Override
    public void destroy() {

    }
    public boolean handllerReq(HttpServletRequest request, HttpServletResponse response) {
        String uri = request.getRequestURI();
        if (StringUtil.isNotBlank(uri) && (uri.startsWith("/restapi/") || uri.startsWith("/api/") )) {
        	String token = JToken.accessToken;
            boolean flagTime = JToken.createTime + (JToken.expires * 1000) < System.currentTimeMillis();
            if(StringUtil.isBlank(token)||flagTime){
                boolean falgLogin = getToken();
               if(!falgLogin){
                   // 登录失败
                   try {
                       PrintWriter writer = response.getWriter();
                       writer.write("登录失败");
                       writer.close();
                       return false;
                   }catch (IOException e){
                       log.error("e:"+e);
                   }
               }
            }
            if(uri.startsWith("/restapi/")){
                try {
                    String data = IOUtils.toString(request.getInputStream());
                    log.info("过滤器请求参数 data :"+data);
                    log.info("过滤器请求路径 uri :"+uri);
                    String newUri = "/"+uri+"?uri="+uri;
                    // 传参
                    request.setAttribute("json",data);
                    request.getRequestDispatcher(newUri).forward(request,response);
                    return false;
                }catch (Exception e){
                    log.error("转发失败"+e.toString());
                }

            }else if(uri.startsWith("/api/")){
                try {
                    String data = IOUtils.toString(request.getInputStream());
                    request.setAttribute("json",data);
                    String newUri = "/testFilter/api?uri="+uri;
                    request.getRequestDispatcher(newUri).forward(request,response);
                    return false;
                }catch (Exception e){
                    log.error("转发失败"+e.toString());
                }
            }
        }
        return true;
    }

    public boolean getToken(){
        OkHttpClient.Builder okBuilder = new OkHttpClient().newBuilder()
                .connectTimeout(10000L, TimeUnit.SECONDS)
                .readTimeout(10000L, TimeUnit.SECONDS)
                .writeTimeout(10000L, TimeUnit.SECONDS);
        // https ssl授权
        JSONObject json = new JSONObject();
        ConfigEntity sConfig = ConfigService.selectOne(new EntityWrapper<ConfigEntity>());
        YZYJToken.id = sConfig.getUid();
        json.put("identifier",sConfig.getIdentifier());
        json.put("credential",sConfig.getCredential());
        json.put("type",sConfig.getAuthType());
        String data = json.toString();

        okBuilder = okBuilder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager());
        OkHttpClient okHttpClient = okBuilder.build();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, data);
        Request.Builder rBudlder= new Request.Builder().url("https://url/restapi/tokens").post(body);

        if(StringUtil.isNotBlank(YZYJToken.refreshToken)){
            rBudlder.addHeader("authorization", "Bearer "+JToken.refresh);
        }
        rBudlder.addHeader("authority", "url");
        rBudlder.addHeader("content-type", "application/json");

        Request request = rBudlder.build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            String reslut = response.body().string();
            log.info("返回结果"+reslut);

            if(reslut.indexOf("token")>-1){
                JSONObject resJson = JSONObject.parseObject(reslut);
                JToken.type = resJson.getString("type");
                JToken.token = resJson.getString("token");
                JToken.expires = resJson.getInteger("expires");
                JToken.refresh = resJson.getString("refresh");
                JToken.createTime = System.currentTimeMillis();
                return true;
            }
        }catch (IOException e){
            log.error("e:"+e);
        }
        return false;
    }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值