Java 中 OutputStream 中字符串中的引号问题

Problem with quotes in String in OutputStream in Java

我有以下问题:如果字符串中有引号或花括号,请求正文不显示字符串。

例如,在这段代码中

HttpContext context = server.createContext("/api/hello", (exchange -> {
    if ("POST".equals(exchange.getRequestMethod())){
        
        ...
        
        OutputStream output = exchange.getResponseBody();
        output.write("{\"number\":12}".getBytes());
        output.flush();
    } else {
        exchange.sendResponseHeaders(405, -1);
    }
}));
    

字符串"{\"number\":12}"不显示。同时,如果我将其更改为字符串 "flower" (不带引号或大括号),则它会正常显示。如何显示像 "{\"number\":12}" 这样的字符串?我需要它在响应正文中显示 JSON。

以下代码片段在提交时发送成功响应POST http://localhost:8383/api/hello

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

import com.sun.net.httpserver.HttpServer;

public class Main {

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 8383), 100);
        server.createContext("/api/hello", (exchange -> {
            System.out.println("Got POST request" + exchange.getRequestURI());
            if ("POST".equals(exchange.getRequestMethod())){

                String json = "{\"message\": \"Hello World!\"}";

                exchange.getResponseHeaders().add("Content-Type", "application/json");
                exchange.sendResponseHeaders(200, json.length());

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

        server.start();
    }
}

回复:

{
    "message": "Hello World!"
}

看来,问题不在于响应的字符串内容,而在于调用 sendResponseHeaders 然后写入输出流:

exchange.sendResponseHeaders(200, json.length());

Content-Type HTTP header 的设置是可选的。