メッセージをデバイスに送信する必要があるシステムのサーバー部分を開発しています。これは GoogleLogin メソッドでは問題なく機能していましたが、他の認証方法が廃止されたため、OAuth 2.0 に移行したいと考えています。
Google API コンソールでプロジェクトを作成し、サービス アカウントのキーを作成しました。
これは、サーバーの認証に使用しているコードです。
public boolean authenticateServer(){
try {
File privateKey =
new File(getClass().getResource("/something-privatekey.p12").toURI());
GoogleCredential cred =
new GoogleCredential.Builder().setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.setServiceAccountId("something@developer.gserviceaccount.com")
.setServiceAccountScopes("https://android.apis.google.com/c2dm")
.setServiceAccountPrivateKeyFromP12File(privateKey)
.addRefreshListener(this)
.build();
boolean success = cred.refreshToken();
this.credential = cred;
return success;
}
catch (Exception ex) {
//handle this
}
return false;
}
これを実行すると、メソッドonTokenResponse
が呼び出され、access_token
with token_type
"Bearer" が 3600 秒で期限切れになります。ここまでは順調ですね。
これは、メッセージをデバイスに送信するために使用しているコードであり、常に 401 ステータス (承認されていません) が表示されます。何か案は?
private static String UTF8 = "UTF-8";
public void sendMessage(String text, String registrationId) {
try {
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder
.append("registration_id")
.append("=")
.append(registrationId);
postDataBuilder.append("&")
.append("collapse_key")
.append("=")
.append("0");
postDataBuilder.append("&")
.append("data.payload")
.append("=")
.append(URLEncoder.encode(text, UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
URL url = new URL("https://android.apis.google.com/c2dm/send");
HostnameVerifier hVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(hVerifier);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty(
"Content-Length", Integer.toString(postData.length));
conn.setRequestProperty(
"Authorization", "Bearer " + credential.getAccessToken());
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int sw = conn.getResponseCode();
System.out.println("" + sw);
}
catch (IOException ex){
//handle this
}
}
ありがとう!