Reputation: 654
My task is to write a simple HTTP client and server, where the latter sends some JSON object to the server. I have decided to use unirest, which is unfortunately poorly documented, but fairly easy to use.
The whole thing works almost as expected, except for one thing - server doesn't read body from POST method, only headers. Sending messages of a different size causes content-length
to change its value, hence the client side is fine. The server's http response is also fine.
How can I fix this?
Server:
public class SimpleHTTPServer {
public static void main(String args[]) throws IOException {
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080 ....");
while (true) {
Socket clientSocket = server.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty()) {
System.out.println(line);
line = reader.readLine();
}
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n";
clientSocket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
clientSocket.close();
}
}
}
Client:
class Client {
void send(String address, String message) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
LocalDateTime localDate = LocalDateTime.now();
String time = dtf.format(localDate);
JSONObject jsonObject = new JSONObject()
.put("time", time)
.put("address", address)
.put("message", message);
try {
HttpResponse<String> postResponse = Unirest.post("http://127.0.0.1:8080")
.header("Accept", "application/json")
.header("Content-type", "application/json")
.body(jsonObject)
.asString();
System.out.println(postResponse.getStatus() + " " + postResponse.getStatusText());
} catch (UnirestException e) {
Alert alert = new Alert(Alert.AlertType.NONE, "Couldn't connect to server!", ButtonType.OK);
alert.showAndWait();
e.printStackTrace();
}
}
}
Output (on server's side):
POST / HTTP/1.1
Accept: application/json
accept-encoding: gzip
Content-type: application/json
user-agent: unirest-java/1.3.11
Content-Length: 66
Host: 127.0.0.1:8080
Connection: Keep-Alive
Upvotes: 1
Views: 330
Reputation: 11020
I think this line is wrong, on the server side:
while (!line.isEmpty()) {
The documentation for BufferedReader
says that it returns null
at end of stream, not an empty string.
Upvotes: 2