Question

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
        //?????????????????????????????
    }
}
Was it helpful?

Solution 2

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);

OTHER TIPS

Is it not just:

Gson gson = new Gson();
String json = gson.toJson(mapResponse);
//Other code to send it back to client
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top