0

I'm receiving an HTTP POST from a remote server on my code, and I have to extract the JSON that comes with it and confirm reception with a response with the 2xx code.

Here's my code:

try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("Server started.\nListening for connections on port : " + PORT + " ...\n");

            JavaServer myServer = new JavaServer(serverSocket.accept());
            System.out.println("Connection opened. (" + new Date() + ")");

            long start_time = System.currentTimeMillis();

            //sendPOST();

            try {
                myServer.run();
            } catch (Exception e) { 
                System.out.println("Error"); 
            }

            long end_time = System.currentTimeMillis();
            System.out.println("Thread took " + (end_time - start_time) / 1000 + " seconds to execute");

            serverSocket.close();
        } catch (IOException e) {
            System.err.println("Server Connection error : " + e.getMessage());
        }
    }

And in the run() method:

public void run() {

        try {
            String urlParameters = "200";
            DataOutputStream wr = new DataOutputStream(connect.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            //wr.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while (in.ready()) {
                inputLine = in.readLine();
                in.read();
                response.append(inputLine);
                System.out.println(inputLine);
            }
            in.close();
            System.out.println("\n"+response.toString());

            wr.close();

        } catch (Exception e) { 
            System.out.println("Error reading input: " + e.getMessage()); 
        }

    }

After searching here for the best solution, I could only find questions related to how to send (not receive) an HTTP POST.

I don't think my code is doing what I want it to do correctly (extract the JSON and send a response back) as it takes long to get a small JSON and I think the response is not being received.

Can anyone help?

Pepe
  • 301
  • 4
  • 13
  • 1
    I'm voting to close this question as off-topic because you should not build you own web-server, but use something already built-in. i.e, https://stackoverflow.com/a/3732328/1790644 – Matt Clark Mar 27 '19 at 22:54
  • Else you should read up on the actual [RFC spec](https://tools.ietf.org/html/rfc2616) and implement this all properly. – Matt Clark Mar 27 '19 at 23:04
  • @MattClark I followed that and it worked, thank you a lot!! – Pepe Mar 28 '19 at 17:40

0 Answers0