2015-11-24 42 views
1

我在將GCM註冊ID添加到我的Android應用的設備組客戶端時出現問題。我遵循https://developers.google.com/cloud-messaging/android/client-device-group的所有說明,但仍然收到401 HTTP響應。我發現下面的職位,但沒有人有答案...基於GCM客戶端的設備組管理

我成功地從得到一個身份驗證令牌GoogleSignInApi和Google的說明中提供的方法,但都會回覆401條回覆。我確保我在Google Developer Console中使用Web應用程序的客戶端ID,但仍然沒有運氣。這裏是我的代碼片段...

URL url = new URL("https://android.googleapis.com/gcm/googlenotification"); 
HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
con.setDoOutput(true); 


// HTTP request header 
con.setRequestProperty("project_id", getString(R.string.gcm_defaultSenderId)); 
con.setRequestProperty("Content-Type", "application/json"); 
con.setRequestProperty("Accept", "application/json"); 
con.setRequestMethod("POST"); 
con.connect(); 

String accountName = getAccount(); 


//Initialize the scope using the client ID you got from the Console. 
final String scope = "audience:server:client_id:" 
        + "MY_WEB_APP_CLIENT_ID"; 
String idToken = ""; 
try { 
    idToken = GoogleAuthUtil.getToken(this, sharedPref.getString("googleEmail", ""), scope); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

// HTTP request 
JSONObject data = new JSONObject(); 
data.put("operation", "add"); 
data.put("notification_key_name", "my_group_name"); 
data.put("registration_ids", new JSONArray(Arrays.asList(registrationId))); 
data.put("id_token", idToken); 

OutputStream os = con.getOutputStream(); 
os.write(data.toString().getBytes("UTF-8")); 
os.close(); 

int responseCode = con.getResponseCode(); 

我不認爲它很重要這個HTTP POST請求,但我也確保了正確的項目和客戶端ID(安卓)存儲在我的谷歌服務。 JSON。有沒有人管理設備組客戶端的任何成功?如果有的話,我的代碼和你的有什麼不同?

+0

試試這個設備組的官方回購點擊這裏:https://github.com/google/gcm/tree/master/samples/android/gcm-demo並抓住一些想法 – bjiang

+0

不幸的是,演示使用使用API​​密鑰的服務器端方法。出於安全原因,我想避免在客戶端使用該密鑰。 –

+0

我有同樣的問題,你有沒有找到解決方案? – greywolf82

回答

0

我不確定沒有服務器API密鑰就可以做到這一點。 401錯誤表示如果該URL用於設備組設置,則應包含某種HTTP授權標頭。

我最好的建議是使用客戶端密鑰存儲機制(http://developer.android.com/training/articles/keystore.html)將服務器API密鑰妥善隱藏。

要詳細瞭解如何做到使用SERVER_API鍵整個事情,請在這裏看到:Google Cloud Messaging (GCM) with local device groups on Android gives HTTP Error code 401

希望這有助於。 :-)

+0

我試圖在客戶端上使用API​​密鑰,但響應始終是來自服務器的401。看來設備組的客戶端已經完全損壞。 – greywolf82