Simple Http Server in Java Using Only Java Se API

Create a simple HTTP server with Java?

Use Jetty. Here's the official example for embedding Jetty. (Here's an outdated tutorial.)

Jetty is pretty lightweight, but it does provide a servlet container, which may contradict your requirement against using an "application server".

You can embed the Jetty server into your application. Jetty allows EITHER embedded OR servlet container options.

Here is one more quick get started tutorial along with the source code.

Official web-server in Java 9

The simple server, found in com.sun.net.httpserver is an official, but optional API in Java 9, located in the module jdk.httpserver. This implies that you can expect it to be maintained in OpenJDK, but not to be available in every JRE.

If you can live with these conditions, you can use it.

How to make POST request with HttpServer?

Correct, the HttpServer class can only handle (client) requests and respond to them.

A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address

If you want to POST a request to another service, you'll need to implement a client to do so using something like HttpClient.

Java Server Side: send Http POST response - status only

It should be enough to send the string HTTP/1.1 200 OK back in your socket-listener.
If you have troubles, you can check out this answer, it shows how to use a HttpServer in Java just via plain JavaSE features.

Java: Simple HTTP Server application that responds in JSON

You could use classes from the package com.sun.net.httpserver:

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class JsonServer {
private static final String HOSTNAME = "localhost";
private static final int PORT = 8080;
private static final int BACKLOG = 1;

private static final String HEADER_ALLOW = "Allow";
private static final String HEADER_CONTENT_TYPE = "Content-Type";

private static final Charset CHARSET = StandardCharsets.UTF_8;

private static final int STATUS_OK = 200;
private static final int STATUS_METHOD_NOT_ALLOWED = 405;

private static final int NO_RESPONSE_LENGTH = -1;

private static final String METHOD_GET = "GET";
private static final String METHOD_OPTIONS = "OPTIONS";
private static final String ALLOWED_METHODS = METHOD_GET + "," + METHOD_OPTIONS;

public static void main(final String... args) throws IOException {
final HttpServer server = HttpServer.create(new InetSocketAddress(HOSTNAME, PORT), BACKLOG);
server.createContext("/func1", he -> {
try {
final Headers headers = he.getResponseHeaders();
final String requestMethod = he.getRequestMethod().toUpperCase();
switch (requestMethod) {
case METHOD_GET:
final Map<String, List<String>> requestParameters = getRequestParameters(he.getRequestURI());
// do something with the request parameters
final String responseBody = "['hello world!']";
headers.set(HEADER_CONTENT_TYPE, String.format("application/json; charset=%s", CHARSET));
final byte[] rawResponseBody = responseBody.getBytes(CHARSET);
he.sendResponseHeaders(STATUS_OK, rawResponseBody.length);
he.getResponseBody().write(rawResponseBody);
break;
case METHOD_OPTIONS:
headers.set(HEADER_ALLOW, ALLOWED_METHODS);
he.sendResponseHeaders(STATUS_OK, NO_RESPONSE_LENGTH);
break;
default:
headers.set(HEADER_ALLOW, ALLOWED_METHODS);
he.sendResponseHeaders(STATUS_METHOD_NOT_ALLOWED, NO_RESPONSE_LENGTH);
break;
}
} finally {
he.close();
}
});
server.start();
}

private static Map<String, List<String>> getRequestParameters(final URI requestUri) {
final Map<String, List<String>> requestParameters = new LinkedHashMap<>();
final String requestQuery = requestUri.getRawQuery();
if (requestQuery != null) {
final String[] rawRequestParameters = requestQuery.split("[&;]", -1);
for (final String rawRequestParameter : rawRequestParameters) {
final String[] requestParameter = rawRequestParameter.split("=", 2);
final String requestParameterName = decodeUrlComponent(requestParameter[0]);
requestParameters.putIfAbsent(requestParameterName, new ArrayList<>());
final String requestParameterValue = requestParameter.length > 1 ? decodeUrlComponent(requestParameter[1]) : null;
requestParameters.get(requestParameterName).add(requestParameterValue);
}
}
return requestParameters;
}

private static String decodeUrlComponent(final String urlComponent) {
try {
return URLDecoder.decode(urlComponent, CHARSET.name());
} catch (final UnsupportedEncodingException ex) {
throw new InternalError(ex);
}
}
}

On a side note, ['hello world!'] is invalid JSON. Strings must be enclosed in double quotes.



Related Topics



Leave a reply



Submit