2017-12-14 2 views
0

Zuul Pre-filter에서 요청 본문에 새 필드를 추가하려고합니다.Netflix Zuul Pre-filter에서 요청 본문에 새 필드 추가

저는 Neflix의 Zuul 샘플 프로젝트 중 하나를 here에서 사용하고 있으며이 필터의 구현은이 샘플의 UppercaseRequestEntityFilter과 매우 유사합니다.

대문자와 같은 변형을 적용하거나 심지어 요청을 완전히 수정할 수도있었습니다. 원래 길이보다 긴 길이의 신체 요청 내용을 수정할 수 없다는 유일한 불편 함이 있습니다. 시체의 요구.

: 이것은 내가받을거야 있다는 응답이

Request Sample

입니다 : 이것은 내가 뭘 요청이

@Component 
public class MyRequestEntityFilter extends ZuulFilter { 
    public String filterType() { 
     return "pre"; 
    } 

    public int filterOrder() { 
     return 10; 
    } 

    public boolean shouldFilter() { 
     RequestContext context = getCurrentContext(); 
     return true; 
    } 

    public Object run() { 
     try { 
      RequestContext context = getCurrentContext(); 
      InputStream in = (InputStream) context.get("requestEntity"); 
      if (in == null) { 
       in = context.getRequest().getInputStream(); 
      } 

      String body = StreamUtils.copyToString(in, Charset.forName("UTF-8")); 

      body = body.replaceFirst("qqq", "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"); 

      // body = body.toUpperCase(); 

      context.set("requestEntity", new ServletInputStreamWrapper(body.getBytes("UTF-8"))); 
     } 
     catch (IOException e) { 
      rethrowRuntimeException(e); 
     } 
     return null; 
    } 
} 

:

이 내 필터의 구현 Response

+0

게시하지 마십시오 이미지를 SO에 ([링크]를 읽을 수 (https://meta.stackoverflow.com/questions : sample-zuul-examples에서, PrefixRequestEntityFilter의 구현을 사용하여, 내가 원하는 것을 얻을 수/285551/why-not-upload-images-of-code-on-so-ask-a-question) 왜 그런지 궁금하다면) –

답변

0

코드의

@Component 
public class MyRequestEntityFilter extends ZuulFilter { 
    public String filterType() { 
     return "pre"; 
    } 

    public int filterOrder() { 
     return 10; 
    } 

    public boolean shouldFilter() { 
     RequestContext context = getCurrentContext(); 
     return true; 
    } 

    public Object run() { 
     try { 
      RequestContext context = getCurrentContext(); 
      InputStream in = (InputStream) context.get("requestEntity"); 
      if (in == null) { 
       in = context.getRequest().getInputStream(); 
      } 

      String body = StreamUtils.copyToString(in, Charset.forName("UTF-8")); 

      body = body.replaceFirst("qqq", "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"); 

      byte[] bytes = body.getBytes("UTF-8"); 

      context.setRequest(new HttpServletRequestWrapper(getCurrentContext().getRequest()) { 
       @Override 
       public ServletInputStream getInputStream() throws IOException { 
        return new ServletInputStreamWrapper(bytes); 
       } 

       @Override 
       public int getContentLength() { 
        return bytes.length; 
       } 

       @Override 
       public long getContentLengthLong() { 
        return bytes.length; 
       } 
      }); 

     } 
     catch (IOException e) { 
      rethrowRuntimeException(e); 
     } 
     return null; 
    } 
} 
관련 문제