Zuul使用Filter修改请求参数、请求头和响应头
修改请求参数
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
Map<String, List<String>> requestQueryParams = ctx.getRequestQueryParams();
if (requestQueryParams == null) {
requestQueryParams = new HashMap<>();
}
//将要新增的参数添加进去,被调用的微服务可以直接 去取,就想普通的一样,框架会直接注入进去
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("1");
requestQueryParams.put("test", arrayList);
ctx.setRequestQueryParams(requestQueryParams);
修改请求头
RequestContext ctx = RequestContext.getCurrentContext();
ctx.addZuulRequestHeader("original_requestURL",request.getRequestURL().toString());
修改响应头
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletResponse response = ctx.getResponse();
String info = response.getHeader("info");
String infoSize = response.getHeader("info_size");
/**
* 设置响应头,使请求变为文件下载
*/
ctx.addZuulResponseHeader("Content-Type", "application/octet-stream");
ctx.addZuulResponseHeader("Content-Disposition", "attachment;fileName=" + info);
ctx.addZuulResponseHeader("Content-Length", "" + infoSize);
重写请求
private void rewriteRequestParams(RoutConfig.Service service) throws Exception {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
Map<String, Object> requestMap = getParams();
// 请求为Get
if (HttpMethod.GET.name().equalsIgnoreCase(request.getMethod())) {
ctx.setRequest(new HttpServletRequestWrapper(request) {
@Override
public String getMethod() {
return HttpMethod.GET.name();
}
});
Map<String, List<String>> r = wrapGetRequestParams();
ctx.setRequestQueryParams(r);
}
// 请求为Post
if (HttpMethod.POST.name().equalsIgnoreCase(request.getMethod())){
//byte[] body = JSON.toJSONBytes(requestMap);
byte[] body = wrapPostRequestBody();
log.info("Post body: {}", new String(body));
ctx.setRequest(new HttpServletRequestWrapper(request) {
@Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStreamWrapper(body);
}
@Override
public int getContentLength() {
return body.length;
}
@Override
public long getContentLengthLong() {
return body.length;
}
@Override
public String getMethod() {
return HttpMethod.POST.name();
}
});
}
}
private Map<String, List<String>> wrapGetRequestParams() {
Map<String, List<String>> r = new LinkedHashMap<>();
r.put("name", Collections.singletonList("Joe.Ye"));
return r;
}
private byte[] wrapPostRequestBody() {
Map<String, Object> requestBody = new LinkedHashMap();
requestBody.put("name", "Joe.Ye");
return JSON.toJSONBytes(requestBody);
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/04/01/zuul-uses-filter-to-modify-request-parameters-request-headers-and-response-headers/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
Zuul使用Filter修改请求参数、请求头和响应头
修改请求参数
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
Map<String, List<String&g……
文章目录
关闭
共有 0 条评论