鍍金池/ 問答/Java  Linux  HTML/ Java創(chuàng)建的HttpServer返回json數(shù)據(jù)

Java創(chuàng)建的HttpServer返回json數(shù)據(jù)

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

在我實(shí)現(xiàn)HttpHandler,重寫handle方法中,
若向responseBody寫入普通字符串(如:"hello"),瀏覽器中訪問該方法可以得到對(duì)應(yīng)的數(shù)據(jù)。
但是寫入json字符串(如:"{"pid":"510229197206267348","pname":"張三"}"),瀏覽器中訪問Status Code: 200 OK,但Status卻是failed.

我猜想應(yīng)該是后臺(tái)header中設(shè)置的數(shù)據(jù)格式類型,但是設(shè)置了headers.set("Content-Type", "application/json; charset=utf-8");也沒有效果。

寫入"{"pid":"510229197206267348","pname":"張三"}"訪問服務(wù)方法截圖:

圖片描述

圖片描述

圖片描述

寫入"hello word"訪問服務(wù)方法截圖:
圖片描述

相關(guān)代碼

public static void main(String[] arg) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0);    
        server.createContext("/post", new BasicPostHttpHandler());        
        // 使用默認(rèn)的 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\":\"張三\"}";   // 寫回這個(gè)數(shù)據(jù)就會(huì)failed
       // String response = "hello world";  // 若寫回這個(gè)數(shù)據(jù)則沒有問題 
        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();
    }

}

你期待的結(jié)果是什么?實(shí)際看到的錯(cuò)誤信息又是什么?

回答
編輯回答
兔囡囡

@半個(gè)夏天 這里我也稍微有一點(diǎn)研究了,你可以去看看我這個(gè) ---> java解析http,可以解決你的問題

2018年7月25日 08:52
編輯回答
夢(mèng)囈

中文字節(jié)的表示問題,

httpExchange.sendResponseHeaders(200, response.length());  改為
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes().length);即可
2017年1月9日 09:30
編輯回答
刮刮樂

跟json沒關(guān)系!你的是中文問題!

2017年1月31日 00:05