如何使用Java中的socket发送JSON响应

时间:2013-06-06 17:36:53

标签: java gson dataoutputstream

我已经构建了一个基本的HTTP服务器,我正在尝试向GET请求发送回复。我已经安装了Gson作为JSON解析器,但我不确定如何在JSON中编码响应并发送回客户端。

这是我的代码,非常感谢任何帮助。 (实际响应的最后一种方法)

public class HttpServer extends Thread{

    //Private variables
    private Socket connectedClient = null;
    private BufferedReader clientRequest = null;
    private DataOutputStream responseToClient = null;

    /**
     * Public constructor
     * @param client
     */
    public HttpServer(Socket client){
        connectedClient =client;
    }

    /**
     * Code to execute on thread
     */
    public void run(){

        try {

            //Log new client
            System.out.println("The client " + connectedClient.getInetAddress() + 
                    ":" + connectedClient.getPort() + " is connected");

            //Get the client request
            clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));

            //Start response object
            responseToClient = new DataOutputStream(connectedClient.getOutputStream());

            //Process the request
            processClientRequest();

            //Close buffered writer
            responseToClient.close();
        } catch (Exception e) {

            //Print error
            e.printStackTrace();
        }
    }

    /**
     * Parses a client request and calls the approriate handler
     * @throws Exception
     */
    private void processClientRequest() throws Exception{

        String requestString = clientRequest.readLine();

        String header = requestString;

        //Break up request
        StringTokenizer tokenizer = new StringTokenizer(header);

        //Different request parts
        String httpMethod = tokenizer.nextToken();
        String httpQueryString = tokenizer.nextToken();

        //Print client request
        StringBuffer responseBuffer = new StringBuffer();
        while (clientRequest.ready()) {
            responseBuffer.append(requestString + " ");
            System.out.println(requestString);

            requestString = clientRequest.readLine();
        }
        //ID GET request
        if (requestString.equals("GET")) {
            if (httpQueryString.equals("/")) {
                sendResponse();

            }   
        }
    }

    /**
     * Sends reply back to client
     * @throws Exception
     */
    private void sendResponse() throws Exception{

        HashMap<String, String> mapResponse = new HashMap<String, String>();
        mapResponse.put("A", "Hands");
        mapResponse.put("B", "Feet");

        //Convert to JSON and send back to client
        //?????????????????????????????
    }
}

2 个答案:

答案 0 :(得分:3)

不只是:

Gson gson = new Gson();
String json = gson.toJson(mapResponse);
//Other code to send it back to client

答案 1 :(得分:3)

你看过GSON的user guide了吗?我怀疑你想要的东西是

Gson gson = new Gson();
String json = gson.toJson(mapResponse); 

要将数据写回套接字,请查看Reading from and Writing to a Socket。这可能有效:

new PrintWriter(responseToClient, true).println(json);