我正在从我的代码中的远程服务器接收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需要很长时间,而且我认为未收到响应。
有人可以帮忙吗?