【发布时间】:2016-05-31 08:03:18
【问题描述】:
我正在使用谷歌端点和谷歌应用引擎开发一个安卓应用程序。我的后端似乎实际上并没有做任何事情。似乎没有任何内容保存到数据存储中,因此无法从中检索任何内容。
以下是我在端点中编写的一些 Api 方法,这些方法不起作用:
private static String getUserId(User user) {
String userId = user.getUserId();
if (userId == null) {
AppEngineUser appEngineUser = new AppEngineUser(user);
ofy().save().entity(appEngineUser).now();
// Begin new session for not using session cache.
Objectify objectify = ofy().factory().begin();
AppEngineUser savedUser = objectify.load().key(appEngineUser.getKey()).now();
userId = savedUser.getUser().getUserId();
}
return userId;
}
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = ApiMethod.HttpMethod.POST)
public Profile saveProfile(final User user, final ProfileForm profileForm) throws UnauthorizedException {
if(user == null) {
throw new UnauthorizedException("Authorization required.");
}
String firstName = profileForm.getFirstName();
String surname = profileForm.getLastName();
String userEmail = user.getEmail();
int year = profileForm.getYear();
int month = profileForm.getMonth();
int day = profileForm.getDay();
Profile profile = ofy().load().key(Key.create(Profile.class, getUserId(user))).now();
if (profile == null) {
// the user does not have a profile and is creating one for the first time
profile = new Profile(getUserId(user), firstName, surname, userEmail, year, month, day);
} else {
profile.update(firstName, surname, userEmail, year, month, day);
}
ofy().save().entity(profile).now();
return profile;
}
@ApiMethod(name = "getProfile", path = "profile", httpMethod = ApiMethod.HttpMethod.GET)
public Profile getProfile(User user) throws UnauthorizedException {
if (user == null) {
throw new UnauthorizedException("Authentication required.");
}
return ofy().load().key(Key.create(Profile.class, getUserId(user))).now();
}
}
profile 类有@Entity 注解,并在一个静态块中使用objectify 注册,如下所示:
static {
factory().register(AppEngineUser.class);
factory().register(Profile.class);
}
userId是GAE通过
生成的com.google.appengine.api.users.User
userId 属性是一个带有@Index 注释的字符串。
我也对 api explorer 以及它如何响应这些方法感到困惑。每当我调用 saveProfile api 方法时,都会返回一个配置文件对象,其中包含 0 的 userId 和 "example@example.com" 的电子邮件,尽管我相信这是在 localhost 上运行时的默认电子邮件。
我也在通过 HTTP 运行 api explorer,谷歌说这“可能会导致问题”。这就是为什么没有任何工作的原因。我必须加载不安全的脚本才能使用我的 api,但它可能不起作用,因为它是通过 HTTP 而不是 HTTPS 托管的。
这整个问题是由于我对 GAE 的理解存在根本缺陷,还是由于我在 localhost 上运行而无法完全测试我的方法。如果是后者,也许我应该部署到 Appspot,事情可能会更顺利。
如果有什么需要帮助的,请尽管问。
谢谢!
【问题讨论】:
标签: java android google-app-engine google-cloud-datastore objectify