使用springcloud的过程中,使用webhook自动发送一个post到configserver,在自己本机上测试可行,但是在码云或者github上就报下边的错误。 {“timestamp”:“2020-12-13T07:01:11.392 00:00”,“status”:400,“error”:“Bad Request”,“message”:"",“path”:"/actuator/bus-refresh/"}
原因: 因为webhook发送post的时候携带了其他的信息,所以可任意用过拦截器把对应的多余的信息拦截掉。
解决方案: 在configserver项目中加一个的webhook的拦截器,然后在主类上加上ServletScanComponent,进行相应的处理即可。
- 添加注解@ServletComponentScan(“com.englishcode.config.interceptors”)
- 编写对应的拦截器
//编写对应的拦截器对webhook发来的连接进行处理
package com.englishcode.config.interceptors;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/**
* @author cyl
* @version 1.0
* @date 2020/12/13 15:26
*/
@Component
public class WebHooksFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String url = new String(httpServletRequest.getRequestURI());
if(!url.endsWith("/bus-refresh")){
filterChain.doFilter(servletRequest,servletResponse);
return;
}
RequestWrapper requestWrapper = new RequestWrapper(httpServletRequest);
filterChain.doFilter(requestWrapper, servletResponse);
}
private class RequestWrapper extends HttpServletRequestWrapper {
public RequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public ServletInputStream getInputStream() throws IOException {
byte[] bytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ServletInputStream servletInputStream = new ServletInputStream() {
@Override
public int read() throws IOException {
return byteArrayInputStream.read();
}
@Override
public boolean isFinished() {
return byteArrayInputStream.read() == -1 ? true : false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener listener) {
}
};
return servletInputStream;
}
}
}
重器配置服务端和客户端进行测试