[英]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
然后寫入 output stream:
exchange.sendResponseHeaders(200, json.length());
Content-Type
HTTP header 的設置是可選的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.