DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Install CMAK, Apache Kafka, Java 18, and Java 19 [Video Tutorials]
  • A Beginner's Guide to Back-End Development
  • Java and Low Latency
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)

Trending

  • Overcoming React Development Hurdles: A Guide for Developers
  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  1. DZone
  2. Coding
  3. Java
  4. A Simple HTTP Server in Java

A Simple HTTP Server in Java

By writing just 100 lines of code, you can develop an HTTP server than can handle HTTP GET and POST requests.

By 
Unni Mana user avatar
Unni Mana
·
Updated Jan. 11, 20 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
185.6K Views

Join the DZone community and get the full member experience.

Join For Free

Do you want to implement an HTTP server, but do you not want to take any risk of writing a full-fledged HTTP server? Developing an HTTP server with full capability is not a trivial task. But Java has got a solution to this kind of problem. Java supports an in-built HTTP server. By just writing 100 lines of code, we can develop a somewhat-decent HTTP server that can handle HTTP GET and POST requests. We can also leverage it to handle other HTTP commands as well.

HTTPServer class

Java SDK provides an in-built server called HttpServer. This class belongs to com.sun.net   package. 

We can instantiate the server like this:

Java
 




xxxxxxxxxx
1


 
1
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8001), 0);



The above line creates an HTTPServer instance on localhost with port number 8001. But, there is one more argument with value 0. This value is used for back logging.


The Complete Java Coder Bundle.*

*Affiliate link. See Terms of Use.

Back Logging

When a server accepts a client request, this request first will be queued by the operating system. Later, it will be given to the server to process the request. All of these simultaneous requests will be queued by the operating system. However, the operating system will decide how many of these requests can be queued at any given point in time. This value represents back logging. In our example, this value is 0, which means that we do not queue any requests.


Server Code

We are going to develop the following HTTP server code:

Java
 




xxxxxxxxxx
1


 
1
server.createContext("/test", new  MyHttpHandler());
2
server.setExecutor(threadPoolExecutor);
3
server.start();
4
logger.info(" Server started on port 8001");



We created a context called, test. This is nothing but the context root of the application. The second parameter is a handler instance, which will handle the HTTP requests. We will look into this class shortly.

We can use a thread pool executor, along with this server instance. In our case, we created a thread pool with 10.

Java
 




xxxxxxxxxx
1


 
1
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)Executors.newFixedThreadPool(10);



Next, we start the server:

Java
 




xxxxxxxxxx
1


 
1
server.start();



With just three to four lines of code, we created an HTTP server with a context root that listens on a port!

HTTPHandler Class

This is an interface with a method called handle(..). Let us take a look at our implementation of this interface.

Java
 




x
44


 
1
private class MyHttpHandler implements HttpHandler {    
2
  @Override    
3
  public void handle(HttpExchange httpExchange) throws IOException {
4
    String requestParamValue=null; 
5
    if("GET".equals(httpExchange.getRequestMethod())) { 
6
       requestParamValue = handleGetRequest(httpExchange);
7
     }else if("POST".equals(httpExchange)) { 
8
       requestParamValue = handlePostRequest(httpExchange);        
9
      }  
10
11
    handleResponse(httpExchange,requestParamValue); 
12
  }
13
14
   private String handleGetRequest(HttpExchange httpExchange) {
15
            return httpExchange.
16
                    getRequestURI()
17
                    .toString()
18
                    .split("\\?")[1]
19
                    .split("=")[1];
20
   }
21
22
   private void handleResponse(HttpExchange httpExchange, String requestParamValue)  throws  IOException {
23
            OutputStream outputStream = httpExchange.getResponseBody();
24
            StringBuilder htmlBuilder = new StringBuilder();
25
            
26
            htmlBuilder.append("<html>").
27
                    append("<body>").
28
                    append("<h1>").
29
                    append("Hello ")
30
                    .append(requestParamValue)
31
                    .append("</h1>")
32
                    .append("</body>")
33
                    .append("</html>");
34
35
            // encode HTML content 
36
            String htmlResponse = StringEscapeUtils.escapeHtml4(htmlBuilder.toString());
37
     
38
            // this line is a must
39
            httpExchange.sendResponseHeaders(200, htmlResponse.length());
40
41
            outputStream.write(htmlResponse.getBytes());
42
            outputStream.flush();
43
            outputStream.close();
44
        }
45
}



This is the code that handles the request and sends the response back to the client. The request and the response is handled by the HttpExchange class.

Handle GET Request

The GET request is handled by the handleGETRequest() method. This method, in turn, calls the getRequestURI() method of HttpExchange class to extract the request parameter value contained in the URI. This is a minimal method that will handle only one parameter present in the request. However, this can be modified to meet different requirements.

Handle Response

Finally, we are going to send our response back to the client. This is achieved by the handleResponse(..) method. In this method, we get the output stream by calling the getResponseBody() method of the HttpExchange class. Later, we can write HTML content to the output stream. 

The most important point is to send a response header  back to the client. If you miss it, you will get an error called  ERR_EMPTY_RESPONSE in the browser.

If all goes well, you can see the response in the browser for a request url:

http://localhost:8001/test?name=sam.


Further Reading

  • Lightweight Embedded Java REST Server Without a Framework.
  • Create and Publish Your Rest API Using Spring Boot and Heroku.
  • Build a Spring Boot App With Secure Server-to-Server Communication Via OAuth 2.0.
Java (programming language) Requests operating system

Opinions expressed by DZone contributors are their own.

Related

  • How To Install CMAK, Apache Kafka, Java 18, and Java 19 [Video Tutorials]
  • A Beginner's Guide to Back-End Development
  • Java and Low Latency
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!