gpt4 book ai didi

java - 发布到 GoogleCloudMessaging 返回 400 InvalidTokenFormat

转载 作者:行者123 更新时间:2023-12-02 09:37:37 25 4
gpt4 key购买 nike

我正在尝试发帖到 Googles Cloud Messaging Api (GCM) ,但我的请求失败,响应为 HTTP/1.1 400 InvalidTokenFormat

但是,如果我更改程序,使其连接到本地主机,并且我只需将其发出的请求通过管道传输到将请求传输到 GCM 的其他设备,则请求会成功。下面是失败的代码:

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStream;

public class GcmPostMe {
public static void main (String[] args) {

String data = "{\"to\":\" *** censored recipient token *** \"}";
String type = "application/json";
try {
URL u = new URL("https://android.googleapis.com/gcm/send/");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Authorization", "key=" + " *** censored api key *** " );
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(data.length()));
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
System.out.println(conn.getResponseCode() + " " + conn.getResponseMessage() );
conn.disconnect();
} catch (Exception e) {
System.err.println("Something went wrong");
}
}
}

当我将上面代码中的 URL 更改为“http://localhost:10000/gcm/send ”并执行操作时,它就起作用了

nc -l 10000 | sed -e "s/localhost:10000/android.googleapis.com/" | openssl s_client -connect android.googleapis.com:443

在运行程序之前。

最佳答案

好吧,我发现了我的错误:路径错误,路径中的尾随 / 不知何故使其无法工作。

执行 HTTP POST 到 https://android.googleapis.com/gcm/send/给你 HTTP/1.1 400 InvalidTokenFormat

http://android.googleapis.com/gcm/send 执行相同的 POST 操作(不带尾随/)成功,HTTP/1.1 200 OK

以下作品:

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStream;

public class GcmPostMe {
public static void main (String[] args) {

String data = "{\"to\":\" *** censored recipient token *** \"}";
String type = "application/json";
try {
URL u = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Authorization", "key=" + " *** censored api key *** " );
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(data.length()));
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
System.out.println(conn.getResponseCode() + " " + conn.getResponseMessage() );
conn.disconnect();
} catch (Exception e) {
System.err.println("Something went wrong");
}
}
}

关于java - 发布到 GoogleCloudMessaging 返回 400 InvalidTokenFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35485755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com