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?