gpt4 book ai didi

java - 如何让Java服务器发送ison响应

转载 作者:行者123 更新时间:2023-11-30 08:45:50 25 4
gpt4 key购买 nike

我是 java 的新手,我想制作一个向客户端发送 json 响应的服务器,我尝试了以下代码,它工作正常。但是当我尝试解析 json 时,它给出了有关内容类型不匹配的问题,如何配置它发送 json 响应?请帮帮我。

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

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Test {

public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/SearchResult", new MyHandler());
server.setExecutor(null);
server.start();
}

static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "{ \"contacts\": [ { \"id\": \"c200\", \"name\": \"Ravi Tamada\", \"email\": \"ravi@gmail.com\", \"address\": \"xx-xx-xxxx,x - street, x - country\", \"gender\" : \"male\", \"phone\": { \"mobile\": \"+91 0000000000\", \"home\": \"00 000000\", \"office\": \"00 000000\" } }, { \"id\": \"c201\", \"name\": \"Johnny Depp\", \"email\": \"johnny_depp@gmail.com\", \"address\": \"xx-xx-xxxx,x - street, x - country\", \"gender\" : \"male\", \"phone\": { \"mobile\": \"+91 0000000000\", \"home\": \"00 000000\", \"office\": \"00 000000\" } } ] }";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}

}

最佳答案

您需要将 Content-Type 指定为 appication/json。

    static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "...JSON...";
httpExchange.getResponseHeaders().set("Content-Type", "application/json");
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}

关于java - 如何让Java服务器发送ison响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33115342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com