3

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")
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
yathirigan
  • 5,619
  • 22
  • 66
  • 104
  • your request object is null ...hence it throws nullpointerexception at the time of calling getreader() method – Angad Tiwari May 05 '15 at 09:48
  • and possibly the case of this post http://stackoverflow.com/questions/3433844/httpservletrequest-how-to-determine-content-type-of-requested-asset – Angad Tiwari May 05 '15 at 09:48

1 Answers1

6

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

rootExplorr
  • 575
  • 3
  • 17
  • i just noticed that , this was happening only for GET request. So how can i get the ContentType for GET requests ? There are few scenarios the GET request sends the parameters as JSON string, rather than query string. I want to differentiate between these 2 scenarios. – yathirigan May 05 '15 at 12:08