【发布时间】:2014-07-23 03:43:01
【问题描述】:
所以,我通过 Dropwizard 获得了这个 Web 服务应用程序。下面是简单的post方法:
@Path(OmniURL.USERPATH)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UserResource {
private final UserMobileDao userMobileDao;
public UserResource(UserMobileDao userMobileDao) {
this.userMobileDao = userMobileDao;
}
@POST
@UnitOfWork
public UserMobile createUserMobile(UserMobile userMobile) {
userMobile.setCreationDate(new Date());
return userMobileDao.save(userMobile);
}
}
这是我试图从 android 应用程序发布的 Json:(最近我通过 Postman 应用程序发布,返回相同的错误,并且他的 ContentType 被正确设置为 'application/json' 作为标题)
{"creationDate":null,"email":"dutfp@hotmail.com","facebookProfile":{"email":"dutfp@hotmail.com","id":"679284068825262"},"id":null,"name":"Jack Et","onlineStoreUser":null}
这代表这个实体:
@Entity
@Table(name = "user_mobile")
public class UserMobile implements Serializable{
private static final long serialVersionUID = -273822158021109237L;
@Id
@SequenceGenerator(name = "seq_user_mobile", sequenceName = "seq_user_mobile", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_user_mobile")
@Column(name = "user_id")
private Long id;
@Column(name = "email", length=30, nullable=false)
private String email;
@OneToOne(optional=true)
private FacebookProfile facebookProfile;
@Column(name = "creation_date")
private Date creationDate;
@OneToOne(fetch=FetchType.LAZY,optional=true)
private OnlineStoreUser onlineStoreUser;
@Column(name = "name", length=30, nullable=false)
private String name;
....getters and setters
}
我已经尝试过如下 CORS 设置:
/* e.servlets().addFilter("cors-filter", CrossOriginFilter.class)
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
*/
Dynamic filter = e.servlets().addFilter("CORS", CrossOriginFilter.class);
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
filter.setInitParameter("allowedOrigins", "*");
filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
filter.setInitParameter("allowedMethods", "GET,PUT,POST,DELETE,OPTIONS");
//filter.setInitParameter("preflightMaxAge", "5184000"); // 2 months
filter.setInitParameter("allowCredentials", "true");
没有成功...
有趣的是,在创建所有实体及其属性之前,我已经使用名称和电子邮件对 UserMobile 进行了测试,它运行良好。所以我相信这是我的一个简单而愚蠢的错误。
【问题讨论】:
-
您确定您的客户端确实在 POST 吗? HTTP 405 错误表明客户端正在尝试 GET 或 PUT 等。这与 Content-Type 无关。我对 CORS 过滤器不太熟悉,但您是否尝试过完全禁用它?
-
是的,我确定我在客户端上发布。关于我已经尝试过的 CORS,只使用上面的注释代码,根本不使用 CORS 过滤器。
标签: java json rest dropwizard