App Engine端点接受请求正文中的POST数据

时间:2016-04-09 23:39:37

标签: google-app-engine

我在App Engine服务器中创建了一个Google端点,如下所示:

package com.xxxxx.gcmbackend;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.api.server.spi.response.CollectionResponse;

import java.util.List;
import java.util.logging.Logger;
import javax.inject.Named;

import static com.xxxxxx.gcmbackend.OfyService.ofy;

@Api(
        name = "register",
        version = "v1",
        namespace = @ApiNamespace(
                ownerDomain = "gcmbackend.xxxxx.com",
                ownerName = "gcmbackend.xxxxx.com",
                packagePath=""
        )
)


public class UserRegistrationEndpoint {
    private static final Logger log = Logger.getLogger(RegistrationEndpoint.class.getName());
    @ApiMethod(name = "register")
    public void registerDevice(@Named("regId") String regId, @Named("username") String username, @Named("phone") String phone) {
        if(findRecord(regId) != null) {
            log.info("Device " + regId + " already registered, skipping register");
            return;
        }
        RegistrationRecord record = new RegistrationRecord();
        record.setRegId(regId);
        record.setUsername(username);
        record.setPhone(phone);
        ofy().save().entity(record).now();
    }
    private RegistrationRecord findRecord(String regId) {
        return ofy().load().type(RegistrationRecord.class).filter("regId", regId).first().now();
    }
}

这非常适合创建新的User记录。 API具有以下格式:

http://example.appspot.com/_ah/api/register/v1/registerDevice/<regId>/<username>/<phone>

但是,我希望网址看起来像这样:

http://example.appspot.com/_ah/api/register/v1/registerDevice/

然后按如下方式发送POST数据:

{
    regId: "some_value",
    username: "some_value",
    phone: "some_value"
}

为了达到这种格式,我需要在终端中更改什么?

1 个答案:

答案 0 :(得分:1)

您需要创建一个包含regIdusernamephone属性的java bean,例如RegistrationInput

public class RegistrationInput {
    private String regId;
    private String username;
    private String phone;

    public String getRegId() {
        return regId;
    }

    public void setRegId(String regId) {
        this.regId = regId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

然后将上面的java bean RegistrationInput作为参数添加到ApiMethod

@ApiMethod(name = "register")
public void registerDevice(RegistrationInput input) {
    .....
}