This seems like such a common use case that there ought to be a simple solution, yet everywhere I look is filled with extremely bloated examples.
Let's say I have a form that looks like:
<form action="http://localhost/endpoint" method="POST" enctype="multipart/form-data">
<input type="text" name="value" />
<input type="submit" value="Submit"/>
</form>
I submit it and on the server want to get the input value:
On the server I set up an HttpServer with a single endpoint, that in this case just sends the body data straight back:
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.*;
import java.net.InetSocketAddress;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(80), 10);
server.setExecutor(null);
server.createContext(
"/endpoint",
(HttpExchange httpExchange) -> {
InputStream input = httpExchange.getRequestBody();
StringBuilder stringBuilder = new StringBuilder();
new BufferedReader(new InputStreamReader(input))
.lines()
.forEach( (String s) -> stringBuilder.append(s + "\n") );
httpExchange.sendResponseHeaders(200, stringBuilder.length());
OutputStream output = httpExchange.getResponseBody();
output.write(stringBuilder.toString().getBytes());
httpExchange.close();
}
);
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now, if submitting the form with the input "hi"
, returns
------WebKitFormBoundaryVs2BrJjCaLCWNF9o
Content-Disposition: form-data; name="value"
hi
------WebKitFormBoundaryVs2BrJjCaLCWNF9o--
This tells me that there should be a way to get the string values, but the only way I can see to do it is to manually parse it.
(Also, I'm trying to get a little dirty, implementing this server only with the libraries that come with the JDK. I've used Apache server quite a bit at work, but that isn't what I'm trying to do here.)