I am trying to read HTTP headers in Spring based REST API. I followed this. But I am getting this error:
No message body reader has been found for class java.lang.String,
ContentType: application/octet-stream
I am new to Java and Spring so can't figure this out.
This is how my call looks like:
@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);
}
I have tried @Context
: HTTPHeader is null
in this case.
How to get values from HTTP headers?
The error that you get does not seem to be related to the RequestHeader.
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
}
And your REST class should have annotations like:
@Controller
@RequestMapping("/rest/")
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.
Example:
@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");
}
Don't worry about the injection of the HttpServletRequest because Spring does that magic for you ;)