importcom.google.appengine.tools.remoteapi.RemoteApiInstaller;importcom.google.appengine.tools.remoteapi.RemoteApiOptions;// ...RemoteApiOptionsoptions=newRemoteApiOptions().server("[APP_ID].[REGION_ID].r.appspot.com",443).useApplicationDefaultCredential();RemoteApiInstallerinstaller=newRemoteApiInstaller();installer.install(options);// ... all API calls executed remotelyinstaller.uninstall();
RemoteApiOptionsoptions=newRemoteApiOptions().server("localhost",8888)// server name must equal "localhost".useDevelopmentServerCredential();
以下是一個完整的 Java 應用程式,此程式在執行時會將實體插入資料儲存庫:
publicclassRemoteApiExample{publicstaticvoidmain(String[]args)throwsIOException{StringserverString=args[0];RemoteApiOptionsoptions;if(serverString.equals("localhost")){options=newRemoteApiOptions().server(serverString,8080).useDevelopmentServerCredential();}else{options=newRemoteApiOptions().server(serverString,443).useApplicationDefaultCredential();}RemoteApiInstallerinstaller=newRemoteApiInstaller();installer.install(options);try{DatastoreServiceds=DatastoreServiceFactory.getDatastoreService();System.out.println("Key of new entity is "+ds.put(newEntity("Hello Remote API!")));}finally{installer.uninstall();}}}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-04 (世界標準時間)。"],[[["\u003cp\u003eThe Java SDK's Remote API allows Java applications to access App Engine services, including the datastore, remotely, even from a local machine or a different App Engine app.\u003c/p\u003e\n"],["\u003cp\u003eThe Remote API server component, a Java servlet, needs to be configured in the \u003ccode\u003eweb.xml\u003c/code\u003e file of the App Engine application to receive requests, dispatch them, and return results.\u003c/p\u003e\n"],["\u003cp\u003eStandalone clients using Remote API require specific JAR files in the classpath and the use of Application Default Credentials via OAuth 2.0, typically set up with the \u003ccode\u003egcloud auth application-default login\u003c/code\u003e command.\u003c/p\u003e\n"],["\u003cp\u003eUsing Remote API involves HTTP round-trips that can be optimized by batching datastore operations, and it incurs usage quota for HTTP requests and datastore operations.\u003c/p\u003e\n"],["\u003cp\u003eWhile transactions are supported with Remote API, they are less efficient due to the need to fetch and verify entities on the server, so it is advised to use them judiciously and try to keep them simple.\u003c/p\u003e\n"]]],[],null,["# Remote API for legacy bundled services\n\nThe Java SDK includes a library called Remote API that lets you transparently\naccess App Engine services from any Java application. For example, you can use\nRemote API to access a production datastore from an app running on your local\nmachine. You can also use Remote API to access the datastore of one App Engine\napp from a different App Engine app.\n| **Important:** Using RemoteApi over a network proxy is not supported.\n| **Caution:** **This solution is no longer recommended:** Apps that use this API can only run in the Java 8 runtime and will need to upgrade to a [recommended solution](/appengine/migration-center/standard/services/migrating-services) before migrating to the Java 11/17 runtime.\n\nConfiguring Remote API on the Server\n------------------------------------\n\nThe server component of Remote API is a Java servlet that is part of the App\nEngine runtime for Java. This servlet receives requests from the Remote API client,\ndispatches them to the appropriate backend service, and then returns the result\nof the service call to the client. To install the Remote API servlet, add the\nfollowing to your `web.xml`: \n\n \u003cservlet\u003e\n \u003cdisplay-name\u003eRemote API Servlet\u003c/display-name\u003e\n \u003cservlet-name\u003eRemoteApiServlet\u003c/servlet-name\u003e\n \u003cservlet-class\u003ecom.google.apphosting.utils.remoteapi.RemoteApiServlet\u003c/servlet-class\u003e\n \u003cload-on-startup\u003e1\u003c/load-on-startup\u003e\n \u003c/servlet\u003e\n \u003cservlet-mapping\u003e\n \u003cservlet-name\u003eRemoteApiServlet\u003c/servlet-name\u003e\n \u003curl-pattern\u003e/remote_api\u003c/url-pattern\u003e\n \u003c/servlet-mapping\u003e\n\n| **Note:** for more information on using `web.xml`, see the [Deployment Descriptor](/appengine/docs/legacy/standard/java/config/webxml) page.\n\nThe servlet returns an error if there is no authenticated user or the\nauthenticated user is not an admin of your application, so there is no need to\nconfigure any additional security. Once you've deployed your app with these\nsettings, any app with the Remote API client installed can use its services.\nThis includes Python clients that are using the Python Remote API.\n\nConfiguring Remote API on a Standalone Client\n---------------------------------------------\n\nTo configure the client component of Remote API for use inside a Java\napplication, add `${SDK_ROOT}/lib/impl/appengine-api.jar` and\n`${SDK_ROOT}/lib/appengine-remote-api.jar` to your classpath. Then, in your\ncode, configure and install Remote API: \n\n import com.google.appengine.tools.remoteapi.RemoteApiInstaller;\n import com.google.appengine.tools.remoteapi.RemoteApiOptions;\n\n // ...\n RemoteApiOptions options = new RemoteApiOptions()\n .server(\"[APP_ID].[REGION_ID].r.appspot.com\", 443)\n .useApplicationDefaultCredential();\n\n RemoteApiInstaller installer = new RemoteApiInstaller();\n installer.install(options);\n // ... all API calls executed remotely\n installer.uninstall();\n\nThe Remote API client will rely on Application Default Credentials that use\nOAuth 2.0.\n\nIn order to get a credential run: \n\n gcloud auth application-default login\n\n| **Note:** The Remote API call to `useApplicationDefaultCredential()` can only use credentials provided by the `gcloud` command.\n\nYou can just as easily connect to an App Engine app running locally in the\n[Development Server](/appengine/docs/legacy/standard/java/tools/using-local-server): \n\n RemoteApiOptions options = new RemoteApiOptions()\n .server(\"localhost\", 8888) // server name must equal \"localhost\"\n .useDevelopmentServerCredential();\n\nHere's a complete Java application that, when run, inserts an Entity\ninto the datastore: \n\n public class RemoteApiExample {\n\n public static void main(String[] args) throws IOException {\n String serverString = args[0];\n RemoteApiOptions options;\n if (serverString.equals(\"localhost\")) {\n options = new RemoteApiOptions().server(serverString,\n 8080).useDevelopmentServerCredential();\n } else {\n options = new RemoteApiOptions().server(serverString,\n 443).useApplicationDefaultCredential();\n }\n RemoteApiInstaller installer = new RemoteApiInstaller();\n installer.install(options);\n try {\n DatastoreService ds = DatastoreServiceFactory.getDatastoreService();\n System.out.println(\"Key of new entity is \" + ds.put(new Entity(\"Hello Remote API!\")));\n } finally {\n installer.uninstall();\n }\n }\n }\n\nConfiguring Remote API on an App Engine Client\n----------------------------------------------\n\nYou can also use Remote API to access the services of one App Engine application\nfrom a different App Engine application. You need to add\n`${SDK_ROOT}/lib/appengine-remote-api.jar` to your `WEB-INF/lib` directory and\nthen, in your client App Engine app, configure and install Remote API just as\nyou did in your standalone Java client.\n\nNotice that `RemoteApiInstaller` only installs Remote API on the thread performing the\ninstallation, so be careful not to share instances of this class across threads.\n\nUsing Remote API with Maven\n---------------------------\n\nTo use the Remote API feature in your Maven project, add the following dependencies\nto your project `pom.xml` file: \n\n \u003cdependency\u003e\n \u003cgroupId\u003ecom.google.appengine\u003c/groupId\u003e\n \u003cartifactId\u003eappengine-remote-api\u003c/artifactId\u003e\n \u003cversion\u003e1.9.64\u003c/version\u003e\n \u003c/dependency\u003e\n \u003cdependency\u003e\n \u003cgroupId\u003ecom.google.appengine\u003c/groupId\u003e\n \u003cartifactId\u003eappengine-api-1.0-sdk\u003c/artifactId\u003e\n \u003cversion\u003e1.9.64\u003c/version\u003e\n \u003c/dependency\u003e\n\nLimitations and best practices\n------------------------------\n\nThe remote_api module goes to great lengths to make sure that as far as\npossible, it behaves exactly like the native App Engine datastore. In some\ncases, this means doing things that are less efficient than they might\notherwise be. When using remote_api, here's a few things to keep in mind:\n\n### Every datastore request requires a round-trip\n\nBecause you're accessing the datastore over HTTP, there's a bit more overhead\nand latency than when you access it locally. In order to speed things up and\ndecrease load, try to limit the number of round-trips you do by batching\ngets and puts, and fetching batches of entities from queries. This is good\nadvice not just for remote_api, but for using the datastore in general,\nbecause a batch operation is only considered to be a single Datastore\noperation.\n\n### Requests to remote_api use quota\n\nBecause the remote_api operates over HTTP, every datastore call you make incurs\nquota usage for HTTP requests, bytes in and out, as well as the usual\ndatastore quota you would expect. Bear this in mind if you're using\nremote_api to do bulk updates.\n\n### 1 MB API limits apply\n\nAs when running natively, the 1MB limit on API requests and responses still\napplies. If your entities are particularly large, you may need to limit the\nnumber you fetch or put at a time to keep below this limit. This conflicts\nwith minimising round-trips, unfortunately, so the best advice is to use the\nlargest batches you can without going over the request or response size\nlimitations. For most entities, this is unlikely to be an issue, however.\n\n### Avoid iterating over queries\n\nWhen you iterate over queries, the SDK fetches entities from the datastore in\nbatches of 20, fetching a new batch whenever it uses up the existing ones.\nBecause each batch has to be fetched in a separate request by remote_api, it's\nunable to do this as efficiently. Instead, remote_api executes an entirely new\nquery for each batch, using the offset functionality to get further into the\nresults.\n\nIf you know how many entities you need, you can do the whole fetch in one\nrequest by asking for the number you need.\n\nIf you don't know how many entities you will want, you can use\n[cursors](/appengine/docs/legacy/standard/java/datastore/query-cursors)\nto efficiently iterate over large result sets. This also\nallows you to avoid the 1000 entity limit imposed on normal datastore\nqueries.\n\n### Transactions are less efficient\n\nIn order to implement transactions via remote_api, it accumulates\ninformation on entities fetched inside the transaction, along with copies of\nentities that were put or deleted inside the transaction. When the\ntransaction is committed, it sends all of this information off to the App\nEngine server, where it has to fetch all the entities that were used in the\ntransaction again, verify that they have not been modified, then put and\ndelete all the changes the transaction made and commit it. If\nthere's a conflict, the server rolls back the transaction and notifies the\nclient end, which then has to repeat the process all over again.\n\nThis approach works, and exactly duplicates the functionality provided by\ntransactions on the local datastore, but is rather inefficient. By all means\nuse transactions where they are necessary, but try to limit the number and\ncomplexity of the transactions you execute in the interest of efficiency."]]