How to send JSON response using socket in Java

不打扰是莪最后的温柔 提交于 2019-12-23 01:19:39

问题


I have built a basic HTTP server and I am attempting to send a reply to a GET request. I have installed Gson as the JSON parser, but I'm not sure how to encode the response in JSON and send back to the client.

Here is my code, any help is much appreciated. (last method for actual response)

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
        //?????????????????????????????
    }
}

回答1:


Have you looked at the user guide for GSON? I suspect you want something along the lines of

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

To write data back to the socket look at Reading from and Writing to a Socket. This might work:

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



回答2:


Is it not just:

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


来源:https://stackoverflow.com/questions/16968595/how-to-send-json-response-using-socket-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!