在JAX-RS资源方法中获取原始请求体 [英] Obtaining raw request body in JAX-RS resource method
问题描述
如何从JAX-RS资源方法访问原始请求正文,如 java.io.InputStream
或 byte []
?我希望容器绕过特定资源类或方法的任何 MessageBodyReader
,但我在项目中有其他资源应该使用一些 MessageBodyReader
。
How can I access the raw request body from a JAX-RS resource method, as java.io.InputStream
or byte[]
? I want the container to bypass any MessageBodyReader
for a specific resource class or method, but I have other resources in the projects which should be using some MessageBodyReader
.
我试过这个,但它会调用已注册的 MessageBodyReader
s并且无法将结果分配给 InputStream
(与 byte []
相同的问题)。
I have tried this, but it will invoke registered MessageBodyReader
s and fail to assign the result to InputStream
(same issue with byte[]
).
@POST
public Response post(@Context HttpHeaders headers, InputStream requestBody) {
MediaType contentType = headers.getMediaType();
// ...
}
我也试过这个,但是然后容器无法初始化此错误:
I have also tried this, but then the container fails to initialize with this error:
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 0
SEVERE: 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();
// ...
}
该方法位于子资源中class,它是从另一个资源类中带有 @Path
注释的方法创建的。
The method is in a sub resource class, which is created from a method with a @Path
annotation in another resource class.
我正在使用Jersey 1.11。
I am using 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();
}
这篇关于在JAX-RS资源方法中获取原始请求体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!