gpt4 book ai didi

java - Jersey ContainerRequestFilter 获取空实体流

转载 作者:行者123 更新时间:2023-12-01 04:33:05 26 4
gpt4 key购买 nike

为了验证 api key ,我使用 ContainerRequestFilter 来读取 JSON 负载并解析 api key 。我有以下方法。

public ContainerRequest filter(ContainerRequest request) {

ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = request.getEntityInputStream();
try {
int read;
final byte[] data = new byte[2048];
while ((read = in.read(data)) != -1)
out.write(data, 0, read);

byte[] requestEntity = out.toByteArray();

request.setEntityInputStream(new ByteArrayInputStream(requestEntity));

if (!validate(new String(data))) {
throw new WebApplicationException(401);
}

return request;
} catch (IOException ex) {
throw new WebApplicationException(401);
}
}

但是,数据总是空白/空。如果没有过滤器,有效负载就会到达资源类并正常工作。关于为什么有效负载为空的任何线索?我正在使用 Firefox 的 REST 客户端以及正文中的 JSON 对此进行测试。

最佳答案

我假设你想打电话

validate(new String(requestEntity))

而不是

validate(new String(data))

因为在第二种情况下,您可能会得到无效的 JSON(如果您的负载足够大)。

此外,您可能需要考虑使用 MessageBodyReaders 为您读取实体:

public ContainerRequest filter(ContainerRequest request) {
// Buffer
InputStream in = request.getEntityInputStream();
if (in.getClass() != ByteArrayInputStream.class) {
// Buffer input
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ReaderWriter.writeTo(in, baos);
} catch (IOException ex) {
throw new ContainerException(ex);
}
in = new ByteArrayInputStream(baos.toByteArray());
request.setEntityInputStream(in);
}

// Read entity as a string.
final String entity = request.getEntity(String.class);

if (!validate(entity) {
throw new WebApplicationException(401);
}

// Reset buffer
ByteArrayInputStream bais = (ByteArrayInputStream)in;
bais.reset();

return request;
}

关于java - Jersey ContainerRequestFilter 获取空实体流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17738035/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com