【问题标题】:Java serversocket(http) reading binary data from a POSTJava serversocket(http) 从 POST 读取二进制数据
【发布时间】:2014-03-24 02:05:58
【问题描述】:

所以,我有一个处理连接请求的网络服务器,在进行任何类型的处理之前,将整个请求存储到一个字符串中(我相信问题在于这里)。

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

        // Loop here until there is no more to read, but wait until the first message arrives.
        while (in.ready() || httpRequestString.isEmpty()) {
            // Read one integer at the time and cast it to a character.
            httpRequestString += (char) in.read();

        }

然后将其发送到 HttpRequest 类进行检查,如果是 POST,则将二进制数据保存到文件中。

适用于文本文件,而不适用于损坏的二进制文件。

我知道您不应该逐行读取二进制文件(特别是使用扫描仪)并使用打印机写入,但我必须检查请求并查找文件内容所在的开始和结束边界,因此我想出了快速的临时代码,只是展示我所拥有的。

scanner = new Scanner(body);
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    if (line.equals("--" + boundary)) {
        fileName = scanner.nextLine().split("filename=")[1].replaceAll("\"", "");
        fileType = scanner.nextLine();
        scanner.nextLine(); //empty line

        PrintWriter fileOutput = new PrintWriter(rootFolder + File.separator + fileName);
        //FileOutputStream fileOutput1= new FileOutputStream(new File(rootFolder + File.separator + fileName));
        String prev = scanner.nextLine();

        while (scanner.hasNextLine()){
            String next = scanner.nextLine();
            System.out.println("reading from: " + prev);
            if (!(next.equals("--" + boundary + "--"))){
                fileOutput.println(prev);
                prev = next;
            }
            else {
                fileOutput.print(prev);
                break;
            }
        }
        fileOutput.close();
    }
}
scanner.close();

如何在开始时存储整个请求,而不丢失进程中的任何字节,并能够检查内容并从中提取二进制数据?

【问题讨论】:

    标签: java post stream inputstream serversocket


    【解决方案1】:

    通过阅读您的 java 源代码,您似乎尝试解析 mime 多部分响应。也许您应该考虑使用 java.mail API。这是关于此 API 的帖子的链接:Read multipart/mixed response in Java/Groovy

    【讨论】:

    • 我认为它不会解决我的问题。我的猜测是我在将 int 转换为 char 时丢失了数据:httpRequestString += (char) in.read();
    猜你喜欢
    • 2018-01-16
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2011-11-27
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多