java - 如何在 Java 中正确处理 HTTP POST
问题描述
我在我的代码上从远程服务器接收 HTTP POST,我必须提取它附带的 JSON,并通过 2xx 代码的响应确认接收。
这是我的代码:
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());
}
}
在 run() 方法中:
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());
}
}
在此处搜索最佳解决方案后,我只能找到与如何发送(不接收)HTTP POST 相关的问题。
我认为我的代码没有做我希望它正确做的事情(提取 JSON 并发送回响应),因为获取一个小的 JSON 需要很长时间,而且我认为没有收到响应。
任何人都可以帮忙吗?
解决方案
推荐阅读
- pivot-table - 使用 powerquery 将具有多列的表还原为具有两列的表,这些列表示原始表中的日期对?
- mongodb - 将值从旧字段迁移到 mongodb 数组中子文档内的新字段
- amazon-s3 - 完成分段上传后访问自定义 S3 元数据
- javascript - ngoninit 上的角度音频播放不起作用
- django - ImageForm 类型的对象不是 JSON 可序列化的
- javascript - 如何在Javascript中通过对象的键过滤对象数组
- html - VueJS Tailwind 自身包含 div 而不会影响其他人
- pivot - 列到行移动标题
- regex - 正则表达式有助于包含字符串的开头,但在结尾排除 2 个值,同时使结果看起来可读
- python - 是否可以制作一个会改变颜色的角色(彩虹角色)