我试图在我的应用中实现一些帖子功能。
我有以下帖子方法:
restrictLoginAttemptsFromSingleIp: function (id, userId) {
var serviceUri = baseServicesUrlService.getBaseServicesUrl() + "/employee-service/restrict-single-ip";
return $http.post(serviceUri, {restrictLoginAttemptIp: {loginAttemptIds: [id]}, dataOwnerId: userId});
}
我的服务器端正在使用RESTEasy 3.0.4和Hibernate验证:
@POST
@Path("/restrict-single-ip")
public Response RestrictSingleIp(@Valid RestrictLoginAttemptIpRequest requestData, @Context HttpRequest request){
return Response.status(200).build();
}
RestrictLoginAttemptIpRequest
类从dataOwnerId
继承了Long
类型的一个字段(PostBase
):
public class RestrictLoginAttemptIpRequest extends PostBase {
private RestrictLoginAttemptIp restrictLoginAttemptIp;
public RestrictLoginAttemptIp getRestrictLoginAttemptIp() {
return restrictLoginAttemptIp;
}
public void setRestrictLoginAttemptIp(RestrictLoginAttemptIp restrictLoginAttemptIp) {
this.restrictLoginAttemptIp = restrictLoginAttemptIp;
}
}
RestrictLoginAttemptIp
类:
package blah;
import org.hibernate.validator.constraints.NotEmpty;
import java.util.List;
public class RestrictLoginAttemptIp {
@NotEmpty(message = "blah")
private List<Long> loginAttemptIds;
public List<Long> getLoginAttemptIds() {
return loginAttemptIds;
}
public void setLoginAttemptIds(List<Long> loginAttemptIds) {
this.loginAttemptIds = loginAttemptIds;
}
}
我从POST请求中获得以下数据字符串似乎没问题:
{restrictLoginAttemptIp={loginAttemptIds=[328]}, dataOwnerId=8}
有人可以解释一下,当我调用该函数时,为什么会出现400 Bad request错误?
这是因为Long数据类型吗?我应该以某种方式在Javascript中将它们标记为Longs?
答案 0 :(得分:0)
4小时后我确定了问题。
案例是,我正在安全拦截器中读取POST数据(解决权限问题)。在RESTEasy中读取POST数据有点棘手。要创建LinkedHashMap
我使用Apache IOUtils(https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html),就像在下一个代码段中找到的那样
String result = IOUtils.toString(requestContext.getEntityStream());
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(result, Object.class);
我查看了我的AngularJS拦截器(例如用于在每个请求的标头中添加内容)并且发现服务器无法读取输入流:java.io.ioexception no content to map to object due to end of input
。
最后问题是,在我读完EntityStream
的{{1}}后,它变空了。解决方案是在读取POST数据后重新填充它。像这样:
ContainerRequestContext
P上。 S. private LinkedHashMap getPostData(ContainerRequestContext requestContext) {
Object obj = null;
try {
String result = IOUtils.toString(requestContext.getEntityStream());
ObjectMapper mapper = new ObjectMapper();
obj = mapper.readValue(result, Object.class);
//IMPORTANT: After you can get the entity stream only once. After reading the entity stream is empty
//so the JSON parser cannot convert EMPTY entity stream into any object. To avoid strange errors (like 400 Bad Request)
//you have to convert the string back to input stream and rewrite the empty entity stream.
InputStream stream = IOUtils.toInputStream(result);
requestContext.setEntityStream(stream);
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
}
return (LinkedHashMap) obj;
}
来自杰克逊