Search code examples
javajsonclientserversocketjava-server

JAVA :I'm not able to send response(json) back to the client from server


I have a client application which send POST request(json) to a custom server. The server must send a response(json) to the incoming message, but i haven't detected any response on the client side.

The problem is not on the client's side, because if it sends a request to another server, then after a few seconds it receives a response and I see it in the logs.

SERVER CODE

        try{
            server = new ServerSocket(4321);
            client = server.accept();
            PrintWriter out = new PrintWriter(client.getOutputStream(), true);
            System.out.println("Connection received from " + client.getInetAddress());
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            String s = "SERVER: Started.";

            Gson gson = new Gson();
            String json = gson.toJson(jsonObject.toString());
            while ((s = in.readLine()) != null) {
              System.out.println("RECV: "+s);
              ss = s.split("PUSH\\s");

              out.println("HTTP/1.1 200 OK");
              out.println("application/json;charset=UTF-8");
              out.println("application/json;charset=UTF-8");
              out.println("Jersey/2.27 (HttpUrlConnection 1.8.0_291)");
              out.println("no-cache");
              out.println("no-cache");
              out.println("hostname:4321");
              out.println("keep-alive");
              out.println("392");
              out.println("\n");
              out.println(json);
            } catch(Exception e) {e.printStackTrace();}

I think the root of my issue is out.println(). I don't know exactly what the server should send back to client. Response must contain json!

Also, i don't have the client code.

Could you help?


Solution

  • While I definitively wouldn't recommend writing an HTTP server this way there are at least two problems in your code:

    1. You are missing header names, e.g. application/json;charset=UTF-8 should read Content-Type: application/json;charset=UTF-8
    2. out.println() uses the line separator string as defined by the system property line.separator (e.g. \n for Linux). HTTP on the other hand needs \r\n, so better write it like this: out.print("HTTP/1.1 200 OK\r\n");

    Try this:

    out.print("HTTP/1.1 200 OK" + "\r\n");
    out.print("Content-Type: application/json" + "\r\n");
    // you shouldn't need the other headers…
    out.print("\r\n");
    out.print(json);