如何获取appengine app的当前服务器URL?
我正在尝试从代码中获取当前运行的appengine java应用程序的服务器URL。 也就是说,如果应用程序在我的本地开发机器上运行,我想以某种方式返回“ http:// localhost:8080 ”但是如果它在prod中运行我想要返回“ http:// myappid。 appspot.com “。 是否有任何java或appengine API可以做到这一点? 我想没有手动更改和读取配置文件或常量。
谢谢。
- 阿利姆
您应该能够使用getServerName():
boolean local = "localhost".equals(httpServletRequest.getServerName());
如果您需要更多信息,还可以使用其他方法,例如getServerPort()。
这对于我在Java上的appengine工作:
String hostUrl; String environment = System.getProperty("com.google.appengine.runtime.environment"); if (StringUtils.equals("Production", environment)) { String applicationId = System.getProperty("com.google.appengine.application.id"); String version = System.getProperty("com.google.appengine.application.version"); hostUrl = "http://"+version+"."+applicationId+".appspot.com/"; } else { hostUrl = "http://localhost:8888"; }
这里有两种方法可以在您的请求处理程序中执行此操作(如果您使用的是提供的webapp
基本框架):
def get(self): self.response.out.write(self.request.headers.get('host', 'no host')) self.response.out.write('
\n') who = wsgiref.util.request_uri(self.request.environ) self.response.out.write(who + '
\n')
这会发出’localhost:8081’或’blabla.appspot.com’作为第一行,而第二行则像完整的URI一样,例如’ http:// localhost:8081 / zup ‘或’ http:// blabla。 appspot.com/zup ‘。
更一般地说,您可以使用wsgiref.util
轻松地从任何WSGI环境中提取信息,并且由于App Engine在WSGI之上提供服务,因此应该总是有简单的方法从您选择的任何框架中撬开这样的环境; – )
我知道这已经得到了回答,但又有另一个人参与其中。
import com.google.apphosting.api.ApiProxy; ... final ApiProxy.Environment env = ApiProxy.getCurrentEnvironment(); final Map attributes = env.getAttributes(); final String hostAndPort = (String) attributes.get("com.google.appengine.runtime.default_version_hostname"); final String url = "http://" + hostAndPort + "/";
参考: https : //cloud.google.com/appengine/docs/java/appidentity/#Java_Asserting_identity_to_other_App_Engine_apps