简体   繁体   English

Java Play Framework 2.0 getHeader()返回null

[英]Java Play Framework 2.0 getHeader() returns null

I'm trying the following code to retrieve a custom HTTP Header but I get null every time. 我正在尝试以下代码来检索自定义HTTP标头但每次都得到null。 Does anybody have any idea why it may not be working? 有没有人知道它为什么不起作用? I've searched high and low but cannot figure out why it is not working. 我搜索了高低,但无法弄清楚为什么它不起作用。

public static Result test() 
    {

        String v = request().getHeader("version");

        System.out.println("test" + v);

return ok("success");
}

I've tested the code using our iPhone app and restclient.jar too so it doesn't seem that the problem is the client not sending the header. 我已经使用我们的iPhone应用程序和restclient.jar测试了代码,所以似乎问题不是客户端没有发送标头。

Any help will be greatly appreciated! 任何帮助将不胜感激!

您的代码可以正常使用curl ,在您的控制台中输入:

curl --header "version: 1.2" localhost:9000/

I banged my head against this one for hours as well. 我也在几个小时内撞到了这个头。 It turns out that Play 2.0 does some odd things with capitalizing HTTP headers. 事实证明,Play 2.0通过大写HTTP标头做了一些奇怪的事情。 Although I sent a header as "Message-Sender-Uid", it showed up in Play as "MESSAGE-SENDER-UID". 虽然我发送了一个标题为“Message-Sender-Uid”,但它在Play中显示为“MESSAGE-SENDER-UID”。 For some reason Play capitalized the whole header. 出于某种原因,Play将整个标题大写。 The solution is to simply look for the all-caps version of your header in the map of headers. 解决方案是在标题地图中查找标题的全大写版本。

If this fails, then you can always just print all of the headers to the Logger to see if your header is even present. 如果失败,那么您始终只需将所有标题打印到Logger,以查看您的标题是否存在。

Something like 就像是

Http.Request req = Http.Context.current().request();
Map<String, String> headerMap = req.headers();
for (String headerKey : headerMap.keySet()) {
    Logger.info("Key: " + headerKey + " - Value: " + headerMap.get(headerKey));
}

in your controller method should work well for this. 在你的控制器方法应该适用于此。

Remember to 记得

import play.mvc.*;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM