我正在使用Jersey 2.x。
以下是我的控制器
@GET
@Path("{id}")
@Produces("application/json")
public Response getUser(@PathParam("id") int userId, @Context ContainerRequestContext containerRequestContext) {
ContainerRequestContext requestContext = logRequest(containerRequestContext);
//To further operations using requestContext
}
以下是我在同一控制器类中记录请求的方法
private ContainerRequestContext logRequest(ContainerRequestContext requestContext) {
JSONObject requestData = new JSONObject();
try {
Map bm = null;
ContainerRequest cr = (ContainerRequest) requestContext;
cr.bufferEntity();
bm = cr.readEntity(Map.class);
if (!String.valueOf(bm).equalsIgnoreCase("null")) {
requestData.put("parameters", bm.toString());
}
requestData.put("uri", requestContext.getUriInfo().getRequestUri());
requestData.put("ClientIp", requestContext.getProperty("requesterIp"));
requestContext.setProperty("requestData", requestData);
} catch (IOException | NumberFormatException | ProcessingException ex) {
//Logging
} catch (Exception ex) {
//Logging
}
return requestContext;
}
正如您所看到的,我正在使用bufferEntity()
多次读取ContainerRequestContext。
在我的服务器上部署API时仍然如此。
我遇到了这个错误:
Error Trace : java.lang.IllegalStateException: Entity input stream has already been closed.
我在这里做错了什么。 如果有人能解释我这种行为,我将感激不尽。
答案 0 :(得分:0)
我有类似的要求,我解决这个问题的方式是克隆"克隆"请求实体,在Apache Commons'的帮助下我喜欢下面的代码片段:
//--- Create a new InputStream with the original entity ---//
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(requestContext.getEntityStream(), baos);
InputStream originalEntity = new ByteArrayInputStream(baos.toByteArray()));
//--- Reasign the original entity to Request Context ---//
requestContext.setEntityStream(new ByteArrayInputStream(baos.toByteArray()));
//--- From this point onwards, you can do whatever you want with the original request entity ---//
. . .
//--- In my case, I am working with JsonObject as below (try/catch ommited for brevity) ---//
JsonReader jsonReader = Json.createReader(originalEntity);
JsonObject requestEntity = jsonReader.readObject();
. . .