gpt4 book ai didi

java - 从 POST 请求中读取正文

转载 作者:可可西里 更新时间:2023-11-01 17:05:07 27 4
gpt4 key购买 nike

我的任务是编写一个简单的 HTTP 客户端和服务器,后者将一些 JSON 对象发送到服务器。我决定使用 unirest ,不幸的是,它的文档很少,但相当容易使用。整个过程几乎按预期工作,除了一件事 - 服务器不从 POST 方法读取正文,仅读取 header 。发送不同大小的消息会导致 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 OK\r\n\r\n";
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,而不是空字符串。

关于java - 从 POST 请求中读取正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49374247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com