简体   繁体   中英

How to receive and extract json in HTTP GET request body

I'm am pretty new to Java and I'm trying to create an API which handles GET requests. The basic code works but without being able to receive any parameters in the body. Most of this code is based on code I've found. What do I need to change if I want to handle json data in the request body?

The working API without parameters:

import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class API {
    public static void main(String[] args) throws IOException {

        String responseText = calculation.data();
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/api", (exchange -> {

            if ("GET".equals(exchange.getRequestMethod())) {

                exchange.sendResponseHeaders(200, responseText.getBytes().length);
                OutputStream output = exchange.getResponseBody();
                output.write(responseText.getBytes());
                output.flush();
            } else {
                exchange.sendResponseHeaders(405, -1);
            }
            exchange.close();
        }));

        server.setExecutor(null);
        server.start();
    }
}

With a proper implementation a GET request method won't accept a body. You can use a handler for a request method that can accept a body (PUT, POST, etc.) ie else if ("POST".equals(exchange.getRequestMethod())) { or pass parameters via URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM