为什么JsonHttpContent的输出为空?

时间:2016-01-19 08:52:21

标签: java json jackson google-http-client

我在Google App Engine(1.9.30)上使用Google Http客户端库(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;
    }
}

最近的目标是生成与(来自Checking the validity of an API key)相同的响应:

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);
}

所有帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

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

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

杰克逊JsonGenerator期望键值配对(在Java中表示为Map),这在JsonHttpContent构造函数的构造函数签名中并不明显:JsonHttpContent(JsonFactory, Object)

因此,如果不是传递GcmDownstreamDto(如问题中所定义的那样,这对ObjectMapper有用),我就会做以下事情:

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

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

{"registration_ids":["ABC"]}

所以请记住将JsonHttpContent(JsonFactory, Object)构造函数作为第二个参数传递给Map<String, Object>,一切都会按照您的预期运行。