服务器在openConnection()之后返回HTTP响应代码:400

时间:2017-11-27 08:08:06

标签: firebase-cloud-messaging

我尝试使用Firebase Cloud Messaging HTTP v1,但是当我在调用openConnection()后收到响应代码时,会返回“404”错误代码

URL url = new URL(FCM_SEND_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
System.out.println("status:" + httpURLConnection.getResponseCode());

我检查了网址中的项目ID,应该是Firebase控制台中的项目ID(设置 - >常规 - >项目ID)

Firebase控制台:

Firebase Console

https://fcm.googleapis.com/v1/projects/xxxxxxxxx/messages:send

更新时间为2017年11月29日

在我的情况下,当我尝试连接到FCM时,我在JSON字符串中使用虚拟标记,导致返回“404”错误代码。
细节可以参考Zaigham Raza提供的链接"HTTP Connection Server Reference And Response Codes" 在JSON字符串中使用真实令牌后,我可以在我的设备上收到通知消息。

错:     {"message":{"notification":{"title":"notification title","body":"message body"},"token":"123"}}

正确:
    {"message":{"notification":{"title":"notification title","body":"message body"},"token":"dwB0YqF......"}}

这里是示例代码

public static HttpURLConnection getHTTPConn() throws Exception{
    URL url = new URL(FCM_SEND_ENDPOINT);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    String token = getAccessToken();
    httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
    httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
    httpURLConnection.setDoOutput(true);
    return httpURLConnection;
}
//The following code to retrieve the token with Google API Client Library <https://firebase.google.com/docs/cloud-messaging/auth-server>
private static String getAccessToken() throws IOException {
    GoogleCredential googleCredential = GoogleCredential
    .fromStream(new FileInputStream("service-account.json"))
    .createScoped(Arrays.asList(SCOPES));
    googleCredential.refreshToken();
    return googleCredential.getAccessToken();
}
public static void sendPushNotificationV1(){
    String result = "";
    try{
        HttpURLConnection conn = getHTTPConn();
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(json.toString());
        wr.flush();
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
        result = "SUCCESS";
    } catch (Exception e) {
        e.printStackTrace();
    }
}

享受〜

0 个答案:

没有答案