我的任务是编写一个简单的HTTP客户端和服务器,后者向服务器发送一些JSON对象。我决定使用 unirest,不幸的是,它的文档很少,但相当容易使用。整个事情几乎按预期工作,除了一件事 - 服务器不从 POST 方法读取正文,只读取标头。发送不同大小的消息会导致content-length
更改其值,因此客户端没问题。服务器的 http 响应也很好。
我该如何解决这个问题?
服务器:
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 OKrnrn";
clientSocket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
clientSocket.close();
}
}
}
客户:
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();
}
}
}
输出(在服务器端(:
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
我认为这行是错误的,在服务器端:
while (!line.isEmpty()) {
BufferedReader
的文档说它在流的末尾返回null
,而不是空字符串。