我正在开发必须向设备发送消息的系统的服务器部分。这适用于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
token_type
“承载”在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
}
}
谢谢!
答案 0 :(得分:2)
由于C2DM目前处于测试阶段状态,因此使用OAuth2.0使其运行的唯一方法是创建Web应用程序客户端ID,而不是服务帐户(在Google API控制台中)。
我已按照http://michsan.web.id/content/how-code-android-c2dm-oauth-2中的步骤进行操作,但效果非常好