繁体   English   中英

如何获取appengine app的当前服务器URL?

[英]How to get the current server URL of appengine app?

我正在尝试从代码中获取当前正在运行的appengine java应用程序的服务器URL。 也就是说,如果应用程序在我的本地开发机器上运行,我想以某种方式返回“ http:// localhost:8080 ”但是如果它在prod中运行我想要返回“ http:// myappid。 appspot.com “。 有没有可以做到这一点的java或appengine API? 我想没有手动更改和读取配置文件或常量。

谢谢。

  • 阿利姆

这对我在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('<br>\n')
    who = wsgiref.util.request_uri(self.request.environ)
    self.response.out.write(who + '<br>\n')

这会发出'localhost:8081'或'blabla.appspot.com'作为第一行,而第二行则像完整的URI一样,例如' http:// localhost:8081 / zup '或' http:// blabla。 appspot.com/zup '。

更一般地说,您可以使用wsgiref.util轻松地从任何WSGI环境中提取信息,并且由于App Engine在WSGI之上提供服务,因此应该总是有简单的方法从您选择的任何框架中撬开这样的环境; - )

您应该能够使用getServerName():

boolean local = "localhost".equals(httpServletRequest.getServerName());

如果您需要更多信息,还可以使用其他方法,例如getServerPort()。

我知道这已经得到了回答,但又有另一个人参与其中;

import com.google.apphosting.api.ApiProxy;

...

final ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
final Map<String, Object> 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM