In my response, I would like to add the size of the JSON to header, Here is what I tried and did not work (the response was empty):
return Response.ok(OBJECT_MAPPER.writeValueAsString(myObject), MediaType.APPLICATION_JSON).header(HttpHeaders.CONTENT_LENGTH), 20).build();
As you can see, I am hard coding the length, but it would be great if I could use the API to do it.
Solution Well, byte size can be returned as below, depending on encoding. Below code would do it without implementing MessageBodyWriter
interface:
String str = OBJECT_MAPPER.writeValueAsString(myObject);
return Response.ok(str , MediaType.APPLICATION_JSON).header(HttpHeaders.CONTENT_LENGTH), str.getBytes("UTF-8").length)).build();
implementing MessageBodyWriter
interface:
String str = OBJECT_MAPPER.writeValueAsString(myObject);
return Response.ok(str , MediaType.APPLICATION_JSON).header(HttpHeaders.CONTENT_LENGTH), str.getBytes("UTF-8").length)).build();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.