Tutorial :How to get the current server URL of appengine app?


I'm trying to get the server URL of a currently running appengine java app from code. That is, if the app is running on my local dev machine I would like to somehow get returned "http://localhost:8080" but if it is running in prod I'd like to be returned "http://myappid.appspot.com". Are there any java or appengine API's that can do this? I'd like to not have a to manually change and read from a config file or a constant.


  • Aleem


You should be able to use getServerName():

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

There are other methods you can also use if you need more info, e.g. getServerPort().


This is working for me in Java on 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";  }  


Here's a couple of way to do it in your request handler (if you're using the provided webapp elementary framework):

  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')  

This emits 'localhost:8081' or 'blabla.appspot.com' as the first line, and as the second like the complete URI instead, e.g. 'http://localhost:8081/zup' or 'http://blabla.appspot.com/zup'.

More generally, you can use wsgiref.util to easily extract info out of any WSGI environment, and since App Engine serves on top of WSGI there should always be easy ways to pry such an environment from the clutches of whatever framework you've chosen;-)


I know this has been answered, but another one to throw in to the mix;

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 + "/";  

Reference: https://cloud.google.com/appengine/docs/java/appidentity/#Java_Asserting_identity_to_other_App_Engine_apps

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »