2

我在 Google App Engine (1.9.30) 上使用 Google Http Client 库 (1.20) 向 Google Cloud Messaging (GCM) 服务器提交 POST 请求。这是代码:

public static HttpRequestFactory getGcmRequestFactory() {
    if (null == gcmFactory) {
        gcmFactory = (new UrlFetchTransport())
                .createRequestFactory(new HttpRequestInitializer() {
                    @Override
                    public void initialize(HttpRequest request) throws IOException {
                        request.getHeaders().setAuthorization(
                                "key=" + Config.get(Config.Keys.GCM_SERVER_API_KEY).orNull());
                        request.getHeaders().setContentType("application/json");
                        request.getHeaders().setAcceptEncoding(null);
                    }
                });
    }
    return gcmFactory;
}

public static JsonFactory getJsonFactory() {
    return jacksonFactory;
}

public static String sendGcmMessage(GcmDownstreamDto message) {
    HttpRequestFactory factory = getGcmRequestFactory();
    JsonHttpContent content = new JsonHttpContent(getJsonFactory(), message);
    String response = EMPTY;
    try {
        HttpRequest req = factory.buildPostRequest(gcmDownstreamUrl, content);
        log.info("req headers = " + req.getHeaders());
        System.out.print("req content = ");
        content.writeTo(System.out); // prints out "{}"
        System.out.println(EMPTY);
        HttpResponse res = req.execute(); // IOException here
        response = IOUtils.toString(res.getContent());
    } catch (IOException e) {
        log.log(Level.WARNING, "IOException...", e);
    }
    return response;
}

现在content.writeTo()总是打印出空的 JSON。这是为什么?我究竟做错了什么?类GcmDownstreamDto(使用 Lombok 生成 getter 和 setter):

@Data
@Accessors(chain = true)
public class GcmDownstreamDto {

    private String to;

    private Object data;

    private List<String> registration_ids;

    private GcmNotificationDto notification;

    public GcmDownstreamDto addRegistrationId(String regId) {
        if (null == this.registration_ids) {
            this.registration_ids = new ArrayList<>();
        }
        if (isNotBlank(regId)) {
            this.registration_ids.add(regId);
        }
        return this;
    }
}

近期目标是生成与(来自检查 API 密钥的有效性)相同的响应:

api_key=YOUR_API_KEY

curl --header "Authorization: key=$api_key" \
       --header Content-Type:"application/json" \
       https://gcm-http.googleapis.com/gcm/send \
       -d "{\"registration_ids\":[\"ABC\"]}"

{"multicast_id":6782339717028231855,"success":0,"failure":1,
"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

我已经测试过,curl所以我知道 API 密钥是有效的,我只想在 Java 代码中做同样的事情来构建我的基类。

sendGcmMessage()被调用如下:

@Test
public void testGcmDownstreamMessage() {
    GcmDownstreamDto message = new GcmDownstreamDto().addRegistrationId("ABC");
    System.out.println("message = " + message);
    String response = NetCall.sendGcmMessage(message);
    System.out.println("Response: " + response);
}

所有帮助表示赞赏。

4

2 回答 2

4

您需要使用以下命令注释 POJO 字段@Key

import com.google.api.client.util.Key;

// ...

@Key private String to;
@Key private Object data;
@Key private List<String> registration_ids;

// ...
于 2016-08-16T13:51:02.640 回答
3

发现了问题:它的工作方式JacksonFactory().createJsonGenerator().searialize()(我期待它以序列化的方式ObjectMapper序列化)。这是JsonHttpContent.writeTo()(来自google-http-java-client 中的 JsonHttpContent.java )的代码:

public void writeTo(OutputStream out) throws IOException {
    JsonGenerator generator = jsonFactory.createJsonGenerator(out, getCharset());
    generator.serialize(data);
    generator.flush();
}

JacksonJsonGenerator期望一个键值对(在 Java 中表示为Map),这在构造函数的构造函数签名中并不明显JsonHttpContentJsonHttpContent(JsonFactory, Object).

因此,如果不是通过 a GcmDownstreamDto(如问题中所定义,这将与 a 一起使用ObjectMapper),我将执行以下操作:

Map<String, Object> map = new HashMap<>();
List<String> idList = Arrays.asList("ABC");
map.put("registration_ids", idList);

一切都按预期工作,输出是:

{"registration_ids":["ABC"]}

所以只要记住传递JsonHttpContent(JsonFactory, Object)构造函数 aMap<String, Object>作为第二个参数,一切都会按照你的预期工作。

于 2016-01-19T09:49:00.617 回答