首页 > 解决方案 > 如何在 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 需要很长时间,而且我认为没有收到响应。

任何人都可以帮忙吗?

标签: javajsonhttppost

解决方案


推荐阅读