0% found this document useful (0 votes)
13 views2 pages

HTTP

Uploaded by

Tejesshree.S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

HTTP

Uploaded by

Tejesshree.S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Lab: 05

Date:
HTTP web server
Aim:
To implement the HTTP web server connection.
Procedure:
1. Create an `HttpServer` on port `8000` and set the context for the root URL (`"/"`) with
`MyHandler` to handle requests.
2. Start the server with `server.start()`.
Handler (MyHandler):
1. Define a response message in the `handle` method.
2. Send the response with `sendResponseHeaders` and write it to the output stream.
3. Close the output stream to finish the response.
Program:
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class SimpleHttpServer
{
public static void main(String[] args) throws IOException
{
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
System.out.println("Server is running on port 8000");
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException
{
String response = "Hello, this is a simple HTTP server response!";
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
Output:

You might also like