如何解决Java中OutputStream中String中的引号问题
我有以下问题:如果字符串中有引号或花括号,请求正文不显示字符串。
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}"
不显示。同时,如果我将其更改为字符串"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 标头的设置是可选的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。