0

我正在嘗試使用遠程API從另一個GAE項目訪問一個應用程序的DataStore。 我使用下面的代碼:GAE HttpResponseException:401

 String serverString = "http://example.com";//this should be the target appengine 
    RemoteApiOptions options; 
    if (serverString.equals("localhost")) { 
     options = new RemoteApiOptions().server(serverString, 8080).useDevelopmentServerCredential(); 
    } else { 
     options = new RemoteApiOptions().server(serverString, 80).useApplicationDefaultCredential(); 
    } 
    RemoteApiInstaller installer = new RemoteApiInstaller(); 

    installer.install(options); 
    datastore = DatastoreServiceFactory.getDatastoreService(); 

    try { 
     results = datastore.get(KeyFactory.createKey("some key")); 
    } catch (EntityNotFoundException e) { 
     e.printStackTrace(); 
     return null; 
    } 

當我運行這個地方,我在installer.install(options);得到一個NullPointerException。 和部署時,從錯誤報告上看到AppEngine上的錯誤是:HttpResponseException: 401 You must be logged in as an administrator, or access from an approved application. 話雖這麼說,我做了的follwing代碼Java小應用程序:

String serverString = "http://example.com";//same string as the one used in the above code 
    RemoteApiOptions options; 
    if (serverString.equals("localhost")) { 
     options = new RemoteApiOptions().server(serverString, 8080).useDevelopmentServerCredential(); 
    } else { 
     options = new RemoteApiOptions().server(serverString, 80).useApplicationDefaultCredential(); 
    } 
    RemoteApiInstaller installer = new RemoteApiInstaller(); 
    installer.install(options); 
    try { 
     DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); 
     System.out.println("Key of new entity is " + ds.put(new Entity("Hello Remote API!"))); 

,這一次的作品!你好新增Remote API實體。

回答

0

在App Engine上運行vs在本地運行時不起作用的原因與正在拾取的憑據有關。在本地運行時,可能使用自己的憑據(可以訪問這兩個項目);相反,在App Engine上運行時,您可能會獲取App Engine默認服務帳戶,該帳戶只能訪問該App Engine項目。

嘗試通過爲包含您希望訪問的雲數據存儲的項目打開Cloud IAM section of Cloud Console來解決此問題。在那裏,授予適用於其他項目正在使用的默認App Engine服務帳戶的訪問級別。

如果您不希望另一個項目中的所有App Engine服務都具有此類訪問權限,那麼您也可以考慮爲此跨項目訪問生成一個service account,您可以授予相應訪問權限(而不是比授予對默認App Engine服務帳戶的訪問權限)。然後,在調用API的代碼中,您可以通過調用RemoteApiOptionsuseServiceAccountCredential()方法明確使用該服務帳戶,以確保發出的API請求使用指定的服務帳戶而不是默認的App Engine服務帳戶。

+0

無法測試這個呢,卡在這裏https://stackoverflow.com/questions/44114233/access-files-in-gae-project –