我正在 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 key 是有效的,我只想在 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);
}
感谢所有帮助。
最佳答案
找到问题了:就是这样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();
}
jackson 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>
作为第二个参数,一切都会按照您的预期工作。
关于java - 为什么 JsonHttpContent 的输出为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34872284/