我已经实现了过滤器,并调用了ContainerRequestContext的getEntityStream并通过使用setEntitystream设置了确切的值。如果我使用此过滤器,则@FormParameter数据将为null,如果我不使用过滤器,则一切都会好起来(因为我没有调用getEntityStream),并且我必须使用过滤器来捕获请求数据。
注意:我从MultivaluedMap formParams获取表单参数,但没有从@FormParameter获取表单参数。
环境:-带有Jboss Wildfly 8服务器的Rest Easy API。
@Provider
@Priority(Priorities.LOGGING)
public class CustomLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter{
final static Logger log = Logger.getLogger(CustomLoggingFilter.class);
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
MDC.put("start-time", String.valueOf(System.currentTimeMillis()));
String entityParameter = readEntityStream(requestContext);
log.info("Entity Parameter :"+entityParameter);
}
private String readEntityStream(ContainerRequestContext requestContext){
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
final InputStream inputStream = requestContext.getEntityStream();
final StringBuilder builder = new StringBuilder();
int read=0;
final byte[] data = new byte[4096];
try {
while ((read = inputStream.read(data)) != -1) {
outStream.write(data, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] requestEntity = outStream.toByteArray();
if (requestEntity.length == 0) {
builder.append("");
} else {
builder.append(new String(requestEntity));
}
requestContext.setEntityStream(new ByteArrayInputStream(requestEntity) );
return builder.toString();
}
return null;
}
}
class customResource
{
//// This code is not working
@POST
@Path("voiceCallBack")
@ApiOperation(value = "Voice call back from Twilio")
public void voiceCallback(@FormParam("param") String param)
{
log.info("param:" + param);
}
// This code is working
@POST
@Path("voiceCallBackMap")
@ApiOperation(value = "Voice call back from Twilio")
public void voiceCallbackMap(final MultivaluedMap<String, String> formParams)
{
String param = formParams.getFirst("param");
}
}
请给我建议解决方案,并在此先感谢。
最佳答案
我在运行时发现(来自http请求的)实体流实例的类型为org.apache.catalina.connector.CoyoteInputStream(我正在使用jboss-as-7.1.1.Final)。但是我们使用java.io.ByteArrayInputStream的实例设置实体流。因此,Resteasy无法绑定单个形式参数。
您可以使用两种解决方案中的任何一种:
使用此方法How to read JBoss Resteasy's servlet request twice while maintaing @FormParam binding?
获取这样的表单参数:
@POST
@Path("voiceCallBackMap")
@ApiOperation(value = "Voice call back from Twilio")
public void voiceCallbackMap(final MultivaluedMap<String, String> formParams)
{
String param = formParams.getFirst("param");
}
关于java - 在读取并设置ContainerRequestContext实体流中的相同数据后,@ FormParameter数据变为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47349109/