gpt4 book ai didi

java - 在 JAX-RS 资源方法中获取原始请求体

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:05 25 4
gpt4 key购买 nike

如何从 JAX-RS 资源方法访问原始请求主体,如 java.io.InputStreambyte[]?我希望容器绕过特定资源类或方法的任何 MessageBodyReader,但我在项目中有其他资源应该使用一些 MessageBodyReader

我已经试过了,但是它会调用已注册的 MessageBodyReader 并且无法将结果分配给 InputStream(与 byte[] 相同的问题>).

@POST
public Response post(@Context HttpHeaders headers, InputStream requestBody) {
MediaType contentType = headers.getMediaType();
// ...
}

我也试过这个,但是容器无法初始化并出现这个错误:

SEVERE: The following errors and warnings have been detected with resource and/or provider classes:SEVERE: Missing dependency for method public javax.ws.rs.core.Response SomeResource.post(javax.servlet.http.HttpServletRequest) at parameter at index 0SEVERE: Method, public javax.ws.rs.core.Response SomeResource.post(javax.servlet.http.HttpServletRequest), annotated with POST of resource, class SomeResource, is not recognized as valid resource method.
@POST
public Response post(@Context HttpServletRequest request) {
String contentType = request.getContentType();
InputStream requestBody = request.getInputStream();
// ...
}

该方法在子资源类中,该子资源类是从另一个资源类中带有 @Path 注释的方法创建的。

我正在使用 Jersey 1.11。

最佳答案

万一这对任何人都有帮助

public Response doAThing(@Context HttpServletRequest request, InputStream requestBody){


BufferedReader reader = new BufferedReader(new InputStreamReader(requestBody));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();

return Response.ok().entity("{\"Submit\": \"Success\"}").build();

}

关于java - 在 JAX-RS 资源方法中获取原始请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16149507/

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