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

谢谢。

  • 阿利姆
有帮助吗?

解决方案

您应该能够使用 getServerName():

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

如果您需要更多信息,还可以使用其他方法,例如获取服务器端口()。

其他提示

这在 appengine 上的 Java 中对我有用:

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 之上,因此应该始终有简单的方法可以从您选择的任何框架的控制中撬开这样的环境;-)

我知道这个问题已经得到了解答,但还有另一个问题需要加入其中;

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归因
不隶属于 StackOverflow
scroll top