FCM Push API返回400 Bad请求

时间:2018-02-01 23:54:14

标签: java android firebase firebase-cloud-messaging

下面是我为发送fcm push创建连接拉取的代码。这个连接在应用程序启动时创建。

private RestTemplate restTemplate;

@PostConstruct
public RestTemplate createRestTemplate() {      
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
     connectionManager.setMaxTotal(3);
     connectionManager.setDefaultMaxPerRoute(3);

    RequestConfig config = RequestConfig.custom().setConnectTimeout(90000).build();
    CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
            .setDefaultRequestConfig(config).build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
    restTemplate = new RestTemplate(factory);
    return restTemplate;
}

以下是发送Push的代码。

json.put("to", target.trim());
        info.put("title","title");
        info.put("body","body");
        json.put("notification", info);

        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "key=" + "mygoogleapikey");
        HttpEntity<String> entity = new HttpEntity<String>(json.toString(), headers);
        String response = restTemplate.postForObject("https://fcm.googleapis.com/fcm/send",entity,String.class);
        JSONObject jsonObj = new JSONObject(response);
        if(jsonObj.getInt("failure") == 0 ) {
            log.info("Success");
        }else {
            log.info("Failed");
        }

我的应用程序正在AWS云上运行,当应用程序启动时它工作正常就意味着将推送发送到设备但是经过一段时间后上面的代码尝试发送推送给我400 Bad Request。

我不明白哪里出错了。

更新 我已经打印了发送到fcm的Json Payload,如下所示

{"notification":{"title":"Test Push","body":"Test Push completed successfully"},"to":"sdffggg:bjvfbmnfjhfgjkdfhgjkhdfmngjmdfhgjkhfjmgbdfmnbmnvbkkk"}

并从Spring Rest Template

获得以下错误
[org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91), org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:615), org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:573), org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529), org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:329)
..............
.................

0 个答案:

没有答案