Java创建的HttpServer返回json数据

问题出现的环境背景及自己尝试过哪些方法

在我实现HttpHandler,重写handle方法中,
若向responseBody写入普通字符串(如:"hello"),浏览器中访问该方法可以得到对应的数据。
但是写入json字符串(如:"{"pid":"510229197206267348","pname":"张三"}"),浏览器中访问Status Code: 200 OK,但Status却是failed.

我猜想应该是后台header中设置的数据格式类型,但是设置了headers.set("Content-Type", "application/json; charset=utf-8");也没有效果。

写入"{"pid":"510229197206267348","pname":"张三"}"访问服务方法截图:

图片描述

图片描述

图片描述

写入"hello word"访问服务方法截图:
图片描述

相关代码

public static void main(String[] arg) throws Exception {

HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0);

server.createContext("/post", new BasicPostHttpHandler());

// 使用默认的 excutor

server.setExecutor(null);

server.start();

}

public class BasicPostHttpHandler implements HttpHandler{

@Override

public void handle(HttpExchange httpExchange) throws IOException {

InputStream is = httpExchange.getRequestBody();

String requestData = is2string(is);

System.out.println("request: " + requestData);

String response = "{\"pid\":\"510229197206267348\",\"pname\":\"张三\"}"; // 写回这个数据就会failed

// String response = "hello world"; // 若写回这个数据则没有问题

System.out.println("response: " + response);

is.close();

Headers headers = httpExchange.getResponseHeaders();

headers.set("Content-Type", "application/json; charset=utf-8");

headers.set("Access-Control-Allow-Origin", "*");

headers.set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");

headers.set("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept");

httpExchange.sendResponseHeaders(200, response.length());

OutputStream os = httpExchange.getResponseBody();

os.write(response.getBytes());

os.close();

}

private String is2string(InputStream is) throws IOException {

final int bufferSize = 1024;

final char[] buffer = new char[bufferSize];

final StringBuilder out = new StringBuilder();

Reader in = new InputStreamReader(is, "UTF-8");

for (; ; ) {

int rsz = in.read(buffer, 0, buffer.length);

if (rsz < 0)

break;

out.append(buffer, 0, rsz);

}

return out.toString();

}

}

你期待的结果是什么?实际看到的错误信息又是什么?

回答:

中文字节的表示问题,

httpExchange.sendResponseHeaders(200, response.length());  改为

httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes().length);即可

回答:

@半个夏天 这里我也稍微有一点研究了,你可以去看看我这个 ---> java解析http,可以解决你的问题

回答:

跟json没关系!你的是中文问题!

以上是 Java创建的HttpServer返回json数据 的全部内容, 来源链接: utcz.com/p/169711.html

回到顶部