Zuul使用Filter修改请求参数、请求头和响应头

修改请求参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);

修改请求头

1
2
RequestContext ctx = RequestContext.getCurrentContext();  
ctx.addZuulRequestHeader("original_requestURL",request.getRequestURL().toString());

修改响应头

1
2
3
4
5
6
7
8
9
10
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);

重写请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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);
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :