【问题标题】:How to determine Content Type of a HTTP Servlet Request?如何确定 HTTP Servlet 请求的内容类型?
【发布时间】:2015-07-14 22:59:47
【问题描述】:

如何在不读取请求正文的情况下从HttpServletRequest 获取内容类型?

当我使用以下内容时,我得到null

request.getContentType()

当我尝试使用以下内容读取请求正文中的 JSON 数据时:

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

request.getReader() 抛出

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

我什至尝试使用以下内容并能够获取内容类型,但在此语句之后从请求中获取读者时仍然得到相同的NullPointerException

request.getHeader("Accept")

【问题讨论】:

标签: json servlets httprequest content-type http-request


【解决方案1】:

您是否正在处理 GET 请求。这可能不包含 Content-Types 标头,因此您在那里看到的是 null。

【讨论】:

  • 我刚刚注意到,这仅发生在 GET 请求中。那么如何获取 GET 请求的 ContentType 呢? GET 请求将参数作为 JSON 字符串而不是查询字符串发送的情况很少。我想区分这两种情况。
猜你喜欢
  • 2011-11-19
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 2015-09-07
  • 2013-12-04
相关资源
最近更新 更多