get App Host Name from HttpServletRequest - Java Network

Java examples for Network:Http

Description

get App Host Name from HttpServletRequest

Demo Code

/*//from   ww  w . j av a  2 s  . c  om
 * AMERICA ONLINE CONFIDENTIAL INFORMATION
 *
 *
 * Copyright (c) 2014 AOL LLC
 *
 * All Rights Reserved.  Unauthorized reproduction, transmission, or
 * distribution of this software is a violation of applicable laws.
 *
 *
 */
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;

public class Main{
    private final static Logger LOG = Logger.getLogger(CommonUtils.class);
    public static String getAppHostName(HttpServletRequest request) {
        String hostName = null;
        try {
            String requestURL = request.getRequestURL().toString();
            String host = requestURL.substring(0,
                    requestURL.indexOf(request.getContextPath()));
            host = host
                    + (request.getContextPath().startsWith("/") ? request
                            .getContextPath() : "/"
                            + request.getContextPath()) + "/";
            hostName = host.endsWith("/") ? host : (host + "/");
            LOG.error("returning url : " + hostName);
            return hostName;
        } catch (Exception e) {
            LOG.error("Error while fetching application Hostname: ", e);
            return null;
        }
    }
}

Related Tutorials