JERSEY:错误跟踪:java.lang.IllegalStateException:实体输入流已关闭

问题描述 投票:0回答:1

我正在使用 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.

我在这里做错了什么。 如果有人能向我解释这种行为,我将不胜感激。

java jersey-2.0
1个回答
0
投票

我有类似的要求,解决这个问题的方法是在 Apache Commons 的 IOUtils 的帮助下“克隆”请求实体,如下面的代码片段:

//--- 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();

. . .
© www.soinside.com 2019 - 2024. All rights reserved.