简体   繁体   English

如何在 HTTP GET 请求正文中接收和提取 json

[英]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.我对 Java 很陌生,我正在尝试创建一个处理GET请求的 API。 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?如果我想处理请求正文中的 json 数据,我需要更改什么?

The working API without parameters:不带参数的工作 API:

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.通过正确的实现,GET 请求方法不会接受正文。 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.您可以将处理程序用于可以接受主体(PUT、POST 等)的请求方法,即else if ("POST".equals(exchange.getRequestMethod())) {或通过 URL 传递参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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