VOOZH about

URL: https://www.javacodegeeks.com/fetching-host-and-port-in-java.html

⇱ Fetching Host and Port in Java - Java Code Geeks


In many Java web applications, there is a need to extract the host name and port from an incoming HTTP or HTTPS request. This is useful for logging, building redirects, generating callback URLs, or working behind reverse proxies. Java provides multiple ways to achieve this depending on the framework and server configuration. Let us delve into understanding how to get the host name and port from a http request in a clear and reliable way in Java.

1. HttpServletRequest Approach

The HttpServletRequest API is the core interface provided by the Java Servlet specification for accessing details of an incoming HTTP request. It exposes several built-in methods that allow developers to directly retrieve the server name, port, and protocol used by the client. These values are especially useful when constructing absolute URLs, performing redirects, logging request metadata, or debugging networking issues. For more details, you can refer to the official Jakarta Servlet Specification. Below are the commonly used methods:

  • getServerName() – returns the hostname the client used to reach your application. For example, example.com, localhost, or an internal load balancer host.See API docs: HttpServletRequest#getServerName()
  • getServerPort() – returns the port number on which the request was received, e.g., 80, 443, or a custom port such as 8080. Documentation: HttpServletRequest#getServerPort()
  • getScheme() – returns the scheme used for the request, typically http or https. Helpful when determining whether the connection is secure. More info: HttpServletRequest#getScheme()

When combined, these methods provide a simple and reliable way to reconstruct the full server address, for example: https://example.com:443. This is often the first approach developers take before moving to more advanced techniques like handling reverse proxies or forwarded headers.

1.1 Code Example

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/host-info")
public class HostInfoServlet extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {

 // Get host, port, scheme
 String host = request.getServerName();
 int port = request.getServerPort();
 String scheme = request.getScheme();

 // Build full host URL
 String fullHost = scheme + "://" + host + ":" + port;

 response.setContentType("text/plain");
 response.getWriter().println("Host: " + host);
 response.getWriter().println("Port: " + port);
 response.getWriter().println("Scheme: " + scheme);
 response.getWriter().println("Full Host URL: " + fullHost);
 }
}

1.1.1 Code Explanation and Output

This Java servlet demonstrates how to extract the host name, port, and scheme from an incoming HTTP or HTTPS request using the HttpServletRequest API. Inside the doGet() method, the servlet calls getServerName() to retrieve the host, getServerPort() to fetch the port number, and getScheme() to determine whether the request is HTTP or HTTPS. These values are combined to form a complete URL string (fullHost) in the format scheme://host:port. Finally, the servlet writes all extracted values back to the client as plain text, making it easy to verify the server information for debugging or request analysis purposes.

Host: localhost
Port: 8080
Scheme: http
Full Host URL: http://localhost:8080

2. Using getRequestURL()

Another convenient approach to obtain host and port information is by using the getRequestURL() method from HttpServletRequest. This method returns a StringBuffer containing the complete URL that the client used to make the request, including the protocol (HTTP/HTTPS), host name, port (if present), and the full servlet path. It is particularly useful when you need the exact external URL without manually combining components, such as during logging, auditing, redirect generation, or when debugging unexpected URL rewrites. More details are available in the official Servlet API documentation.

Using this method simplifies extraction because you are reading the entire URL in one call. If needed, developers can further parse this URL using Java’s java.net.URL class to extract scheme, host, port, or path components individually. This is especially handy in scenarios involving dynamic URL building, deep links, or integration callbacks where the application must know the precise URL that was hit.

2.1 Code Example

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/full-url")
public class FullUrlServlet extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {

 // Get the full request URL
 StringBuffer url = request.getRequestURL();
 String fullUrl = url.toString();

 response.setContentType("text/plain");
 response.getWriter().println("Full Request URL: " + fullUrl);
 }
}

2.1.1 Code Explanation and Output

This Java servlet shows how to retrieve the complete URL of an incoming HTTP request using the HttpServletRequest.getRequestURL() method, which returns a StringBuffer containing the full path including scheme, host, port, and servlet mapping. Inside the doGet() method, the servlet converts this StringBuffer to a string and writes it back to the client as plain text, allowing developers to easily verify the exact URL that was requested—useful for logging, debugging, redirects, or building dynamic links.

Full Request URL: http://localhost:8080/full-url

3. Spring URI Builder Method

Spring provides the ServletUriComponentsBuilder utility class as part of the Spring Web MVC framework to help developers construct URLs in a clean, framework-friendly, and highly customizable manner. Unlike the plain HttpServletRequest methods, this builder abstracts away low-level string manipulation and gives you a fluent API to extract or construct parts of a request URL. It automatically reads information from the current request context and returns UriComponents, which expose host, port, scheme, path, and query parameters in a structured format.

A common use case is retrieving the host and port of the active request. With a single call like ServletUriComponentsBuilder.fromCurrentRequest().build(), developers can access getHost(), getPort(), getScheme(), or even rebuild fully-qualified URLs. This approach fits naturally into Spring Boot applications, especially when building REST APIs that need to generate callback URLs, pagination links, HATEOAS resources, or dynamic redirect URLs. Using this builder ensures consistency with Spring’s request handling pipeline and avoids low-level parsing errors.

3.1 Code Example

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@SpringBootApplication
public class HostPortApplication {
 public static void main(String[] args) {
 SpringApplication.run(HostPortApplication.class, args);
 }
}

@RestController
class HostPortController {

 @GetMapping("/host-port")
 public String getHostAndPort() {

 String hostWithPort = ServletUriComponentsBuilder
 .fromCurrentRequest()
 .build()
 .getHost() + ":" +
 ServletUriComponentsBuilder
 .fromCurrentRequest()
 .build()
 .getPort();

 return "Host with Port: " + hostWithPort;
 }
}

3.1.1 Code Explanation and Output

This Spring Boot example demonstrates how to extract the host and port from the current HTTP request using ServletUriComponentsBuilder, which builds URI components from the active request context. Inside the controller’s /host-port endpoint, the code calls fromCurrentRequest().build() to obtain a UriComponents object and then retrieves the host and port using getHost() and getPort(), finally concatenating both into a single host:port string. This approach is useful when constructing dynamic URLs, redirects, or logging request metadata in Spring-based applications.

Host with Port: localhost:8080

4. Handling Reverse Proxies

When applications run behind load balancers, API gateways, or reverse proxies such as Nginx, Apache HTTP Server, AWS Application Load Balancer (ALB), or cloud platforms like Cloudflare and GCP Load Balancing, the server-reported values (getServerName(), getServerPort(), getScheme()) may not represent the original client-facing URL. This happens because traffic is terminated or modified by your proxy layer before reaching your backend container/VM.

To preserve the actual external request information, proxies send special headers that reflect the original protocol, host, and port used by the client. These forwarded headers allow backend applications to reconstruct the real URL, which is essential for generating accurate redirects, forming absolute links, performing logging, or validating callback URLs in OAuth/webhooks. Common reverse proxy headers include:

  • X-Forwarded-Host – contains the original hostname requested by the client (e.g., example.com, api.myapp.com). More details: MDN Docs
  • X-Forwarded-Port – specifies the external port used by the client (e.g., 80, 443, 8443).Reference: MDN Docs
  • X-Forwarded-Proto – indicates whether the original request was http or https. This is especially important for apps behind SSL-terminating load balancers. Documentation: MDN Docs

By reading and combining these header values, applications can accurately reconstruct the public-facing URL, avoiding common issues like incorrect redirect URLs or mixed-content warnings caused by mismatched HTTP/HTTPS protocols.

4.1 Code Example

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/proxy-host-info")
public class ProxyHostInfoServlet extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {

 // Read X-Forwarded-* headers
 String forwardedHost = request.getHeader("X-Forwarded-Host");
 String forwardedPort = request.getHeader("X-Forwarded-Port");
 String forwardedProto = request.getHeader("X-Forwarded-Proto");

 // Build host:port URL from proxy headers
 String hostPort = forwardedProto + "://" + forwardedHost + ":" + forwardedPort;

 response.setContentType("text/plain");
 response.getWriter().println("X-Forwarded-Host: " + forwardedHost);
 response.getWriter().println("X-Forwarded-Port: " + forwardedPort);
 response.getWriter().println("X-Forwarded-Proto: " + forwardedProto);
 response.getWriter().println("Reconstructed URL: " + hostPort);
 }
}

4.1.1 Code Explanation and Output

This servlet demonstrates how to correctly read reverse-proxy headers such as X-Forwarded-Host, X-Forwarded-Port, and X-Forwarded-Proto, which are added by load balancers or proxies to indicate the original client-facing URL. Inside the doGet() method, the servlet retrieves these header values using request.getHeader() and then reconstructs the actual external URL by combining protocol, host, and port into a single string. This approach is essential when your backend server is running behind proxies and needs to generate accurate external URLs for redirects, links, or logging.

X-Forwarded-Host: example.com
X-Forwarded-Port: 443
X-Forwarded-Proto: https
Reconstructed URL: https://example.com:443

5. Conclusion

Extracting the host name and port from HTTP/HTTPS requests in Java can be done in multiple ways depending on your environment. For simple servlet-based applications, the HttpServletRequest API is enough. For Spring applications, ServletUriComponentsBuilder provides cleaner handling. When running behind reverse proxies, always consider the X-Forwarded-* headers to reconstruct the original request information accurately.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

Tags
Java port
👁 Photo of Yatin Batra
Yatin Batra
November 13th, 2025Last Updated: November 13th, 2025
0 1,240 6 minutes read

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz