发布到GoogleCloudMessaging会返回400 InvalidTokenFormat

我正在尝试发布到谷歌云消息传递Api(GCM) ,但我的请求失败,响应HTTP/1.1 400 InvalidTokenFormat

但是,如果我改变我的程序以便它连接到localhost,而我只是将请求传递给其他将请求发送到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 

在我运行程序之前。

好吧,我发现了我的错误:路径错了,路径中的尾随/某种方式使它无法正常工作。

对https://android.googleapis.com/gcm/send/执行HTTP POST会为您提供HTTP / 1.1 400 InvalidTokenFormat

使用HTTP / 1.1 200对http://android.googleapis.com/gcm/send (没有尾随/)执行相同的POST成功

以下作品:

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