【问题标题】:Problem with quotes in String in OutputStream in JavaJava中OutputStream中字符串中的引号问题
【发布时间】:2021-04-02 16:28:14
【问题描述】:

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

例如在这段代码中

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。

【问题讨论】:

    标签: java json post backend outputstream


    【解决方案1】:

    以下代码sn-p在提交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 标头的设置是可选的。

    【讨论】:

    • 谢谢你,亚历克斯,它有效! :)。事实上,代码行 exchange.sendResponseHeaders(200, json.length()); 原来是显示 JSON 响应所必需的。行exchange.getResponseHeaders().add("Content-Type", "application/json"); 确实显示得更漂亮。
    • 对于读者,我想注意这一行json(例如json.length())必须是您正在打印的行。
    猜你喜欢
    • 1970-01-01
    • 2010-10-16
    • 2011-08-16
    • 2015-09-14
    • 2012-11-18
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多