springcloud zuul修改请求参数支持get和post
作者:互联网
1、code
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import org.springframework.util.StreamUtils;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @author code
* @version 1.0
* @Date 2021/12/21 9:14
* @Description ${参数过滤器}
*/
public class ParamFilter extends ZuulFilter {
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 2;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
String method = ctx.getRequest().getMethod();
if("GET".equals(method.toUpperCase())){
Map<String, List<String>> param = ctx.getRequestQueryParams();
if(Objects.isNull(param) || param.isEmpty()){
param = Maps.newHashMap();
}
param.put("accessKey", Arrays.asList("test"));
param.put("secretKey", Arrays.asList("123456"));
ctx.setRequestQueryParams(param);
}else if("POST".equals(method.toUpperCase())){
String charSet = ctx.getRequest().getCharacterEncoding();
try{
InputStream inputStream = ctx.getRequest().getInputStream();
String body = StreamUtils.copyToString(inputStream, Charset.forName(charSet));
JSONObject param = JSONObject.parseObject(body);
if(Objects.isNull(param) || param.isEmpty()){
param = new JSONObject();
param.put("secret_key","ddd");
param.put("access_key","ddd");
}
final byte[] paramBytes = param.toJSONString().getBytes(charSet);
rewriteRequest(ctx, paramBytes);
ctx.addZuulRequestHeader("Content-type", "application/json");
}catch (IOException e){
e.printStackTrace();
}
}
return null;
}
public static void rewriteRequest(RequestContext ctx, byte[] paramBytes){
ctx.setRequest(new HttpServletRequestWrapper(ctx.getRequest()){
@Override
public ServletInputStream getInputStream() throws IOException{
return new ServletInputStreamWrapper(paramBytes);
}
@Override
public int getContentLength(){
return paramBytes.length;
}
@Override
public long getContentLengthLong(){
return paramBytes.length;
}
});
}
}
2、post提交时参数需要设置content-type
ctx.addZuulRequestHeader("Content-type", "application/json");
以json的格式传递至controller
标签:java,zuul,get,springcloud,ctx,param,return,import,public 来源: https://blog.csdn.net/yy1209357299/article/details/122060913