Problem with quotes in String in OutputStream in Java

Viewed 103

I have the following problem: the request body does not display a string if there are quotes or curly braces in the string.

For example, in this code

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);
    }
}));
    

string "{\"number\":12}" does not display. At the same time if I change it to string "flower" (without quotes or curly braces), then it displays normally. How to display a string like "{\"number\":12}" ? I need it to display JSON in the response body.

1 Answers

The following code snippet sends a successful response when submitting 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();
    }
}

Response:

{
    "message": "Hello World!"
}

It seems, the issue is not with the string contents of the response but with making a call to sendResponseHeaders followed by writing to the output stream:

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

Setting of Content-Type HTTP header is optional.

Related