在Spring REST控制器中读取HTTP头 [英] Reading HTTP headers in a Spring REST controller

查看:472
本文介绍了在Spring REST控制器中读取HTTP头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在基于Spring的REST API中读取HTTP头。我跟着这个。但我收到此错误:

I am trying to read HTTP headers in Spring based REST API. I followed this. But I am getting this error:


没有找到类java.lang.String的消息正文阅读器,

ContentType:application / octet-stream

No message body reader has been found for class java.lang.String,
ContentType: application/octet-stream

我是Java和Spring的新手,所以无法理解这一点。

I am new to Java and Spring so can't figure this out.

这就是我的通话方式:

@WebService(serviceName = "common")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public interface CommonApiService {

    @GET
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/data")
    public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @DefaultValue ("") @QueryParam("ID") String id);
}

我试过 @Context :在这种情况下,HTTPHeader是 null

I have tried @Context: HTTPHeader is null in this case.

如何从HTTP标头中获取值?

How to get values from HTTP headers?

推荐答案

您获得的错误似乎与 RequestHeader 无关。

The error that you get does not seem to be related to the RequestHeader.

您似乎将Spring REST服务与 JAX-RS 混淆,你的方法签名应该是这样的:

And you seem to be confusing Spring REST services with JAX-RS, your method signature should be something like:

@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @RequestParam(value = "ID", defaultValue = "") String id) {
    // your code goes here
}

您的REST类应该有以下注释:

And your REST class should have annotations like:

@Controller
@RequestMapping("/rest/")



关于实际问题,获取HTTP头的另一种方法是插入 HttpServletRequest 进入您的方法,然后从那里获得所需的标题。


Regarding the actual question, another way to get HTTP headers is to insert the HttpServletRequest into your method and then get the desired header from there.

示例:

@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(HttpServletRequest request, @RequestParam(value = "ID", defaultValue = "") String id) {
    String userAgent = request.getHeader("user-agent");
}

不要担心注入 HttpServletRequest 因为Spring为你做了那个魔术;)

Don't worry about the injection of the HttpServletRequest because Spring does that magic for you ;)

这篇关于在Spring REST控制器中读取HTTP头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆