2016-11-29 64 views
4

我正在尝试在泽西岛的MessageBodyReader中读取APPLICATION_FORM_URLENCODED。当我尝试使用读它的流返回null数据BufferedReaderInputStream在MessageBodyReader中提供空数据Jersey

这里是我的代码:

@Consumes(MediaType.APPLICATION_FORM_URLENCODED) 
public class EmployeeReader implements MessageBodyReader<Employee> { 

    @Override 
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, 
     MediaType mediaType) { 
     return true; 
    } 

    @Override 
    public Employee readFrom(Class<Employee> type, Type genericType, Annotation[] annotations, 
     MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) 
     throws IOException, WebApplicationException { 
     System.out.println(entityStream.available()); //Prints 0 
     BufferedReader br = new BufferedReader(new InputStreamReader(entityStream)); 
     String data = br.readLine(); 
     System.out.println("Stream Read:"+data); 
     //data is null here 
     ..... 
    } 
} 

我可以看到数据是从我的形式发送POST请求为application/x-www-form-urlencoded,但是我无法在我的MessageBodyReader中看到它。

在调试我可以看到ByteChunk持有以下数据:

POST /Employees/employee HTTP/1.1 
host:localhost:80800 
connection:keep-alivee 
content-length:144 
postman-token:cf873d98-3208-292c-8fc1-6da8138a31faa 
cache-control:no-cachee 
origin:chrome-extension://fhbjgbiflinjbdggehcddcbncdddomopp 
user-agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.366 
content-type:application/x-www-form-urlencodedd 
accept:*/** 
accept-encoding:gzip, deflate, brr 
accept-language:en-US,en;q=0.88 

id=3&name=Test 

UPDATE

我才发现,这是某种的SpringBootServletInitializer副作用。禁用此功能会导致上述代码正常工作。

任何人都可以帮忙吗?

+0

POST参数在Servlet到达作为请求的参数,而不是作为消息体的InputStream将不被读取。 – EJP

+0

@EJP我已经看到泽西岛2.5在独立泽西岛应用程序相同的代码工作,这个代码是不是在Jersey 2.23与春季启动工作,此外,正如我在问题中提到的,我可以看到数据(发布在问题)在调试控制台中的InputStream的ByteChunk中('id = 3&name = Test') –

回答

4

显然有一个HiddenHttpMethodFilter在请求到达表单数据代码和POST请求之前没有getParameter。所以InputStream已被阅读,br.readLine();返回null

我找到了一种方法在其他职位的一个重写此here

@Configuration 
public class FilterConfig { 
    @Bean 
    public HiddenHttpMethodFilter hiddenHttpMethodFilter() { 
     return new HiddenHttpMethodFilter() { 
      @Override 
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
        FilterChain filterChain) throws ServletException, IOException { 
       if ("POST".equals(request.getMethod()) 
         && request.getContentType().equals(MediaType.APPLICATION_FORM_URLENCODED)) { 
        //Skip this filter and call the next filter in the chain. 
        filterChain.doFilter(request, response); 
       } else { 
        //Continue with processing this filter. 
        super.doFilterInternal(request, response, filterChain); 
       } 
      } 
     }; 
    } 
} 

那么这样做是它只是检查,如果该请求是POST型的,如果的MediaType是APPLICATION_FORM_URLENCODED,如果是这样那么我们会跳过这部分过滤器链,否则我们也会处理这个过滤器。

这样当它到达MessageBodyReader