【问题标题】:Recive POST data by http server通过http服务器接收POST数据
【发布时间】:2018-08-03 18:58:29
【问题描述】:

我在 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

【问题讨论】:

  • 你能把你要解析的json或数据的结构贴出来吗?
  • @GastónSaillén 它只是没有 json 的文本数据
  • I have simple http server on android from Android Samples. 请提供链接,以便我们查看您正在使用的内容。
  • @greenapps 嘿,查看完整的代码链接。

标签: java android http server


【解决方案1】:

一般来说,http 请求是一个文本片段。请求的类型在文本中指明。因此,在 GET 请求中,您提供的示例首先会找到“GET”字符串。然后解析get请求。 POST 也应该这样做。首先识别“POST”,然后解析请求的其余部分。

【讨论】:

  • 不。我做到了。什么都看不见。仅 POST 带有标题。然后 JS 控制台报错。
  • 也许您应该发布您尝试过的内容。 JS 控制台中的任何错误都与您返回的响应有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多