我正在尝试发布到Googles Cloud Messaging 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");
}
}
}
当我将上面代码中的网址更改为“http://localhost:10000/gcm/send”并执行
时,它可以正常工作nc -l 10000 | sed -e "s/localhost:10000/android.googleapis.com/" | openssl s_client -connect android.googleapis.com:443
在我运行程序之前。
答案 0 :(得分:11)
好的,我发现了我的错误:路径错了,路径中的尾随/
不知何故使它无效。
对https://android.googleapis.com/gcm/send/执行HTTP POST会为您提供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");
}
}
}