通过http服务器重新发送POST数据

时间:2018-02-23 16:47:21

标签: java android http server

我在Android样本上安装了简单的http服务器。我喜欢这个服务器,所以我也希望从浏览器中恢复POST数据。如何用标准的东西(没有外部库)来回收它?我尝试像GET一样重温它,但是js控制台显示连接错误。

private void handle(Socket socket) throws IOException {
    BufferedReader reader = null;
    PrintStream output = null;
    try {
        String route = null;

        // Read HTTP headers and parse out the route.
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while (!TextUtils.isEmpty(line = reader.readLine())) {
            if (line.startsWith("GET /")) {
                int start = line.indexOf('/') + 1;
                int end = line.indexOf(' ', start);
                route = line.substring(start, end);
                break;
            }
        }

        // Output stream that we send the response to
        output = new PrintStream(socket.getOutputStream());

        // Prepare the content to send.
        if (null == route) {
            writeServerError(output);
            return;
        }
        byte[] bytes = loadContent(route);
        if (null == bytes) {
            writeServerError(output);
            return;
        }

        // Send out the content.
        output.println("HTTP/1.0 200 OK");
        output.println("Content-Type: " + detectMimeType(route));
        output.println("Content-Length: " + bytes.length);
        output.println();
        output.write(bytes);
        output.flush();
    } finally {
        if (null != output) {
            output.close();
        }
        if (null != reader) {
            reader.close();
        }
    }
}

full code

1 个答案:

答案 0 :(得分:0)

通常,http请求是文本片段。请求的类型在文本中指出。因此,在GET请求中,您首先提供的示例会找到" GET"串。然后解析get请求。 POST也应该这样做。首先确定" POST"然后解析剩下的请求。

相关问题