How to determine Content Type of a HTTP Servlet Re

2019-05-18 16:50发布

问题:

How can I get the content type from the HttpServletRequest without reading the request body?

When I use the following, I get null:

request.getContentType()

When I try to read the JSON data that comes in the request body using the following:

StringBuilder jsonsb = new StringBuilder();
BufferedReader jsonbr = request.getReader();

The request.getReader() throws

Caused by: java.lang.NullPointerException: null
    at java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:106)

I even tried using the following and was able to get the content type but, still getting the same NullPointerException while getting the reader from request after this statement.

request.getHeader("Accept")

回答1:

Are you handling a GET request. That might not contain a Content-Types header and therefore you are seeing a null there.