Java HTTP 客户端用于上传文件(multipart/form-data)

6
我正在尝试实现一个HTTP客户端,用于上传文件到HTTP服务器的多部分请求。HTML表单有三个输入字段:一个用于用户名,一个用于密码,一个用于文件。服务器端如下所示。
<html>
<head>
<title>Uploader</title>
</head>

<body>
   <div id="header">
         <h1>Uploader</h1>
   </div>
   <div id="content">
         <form id="uploadformular" action="upload" method="post"
                enctype="multipart/form-data" accept-charset="utf-8">
                <div class="block">
                       <label for="user">Username</label> <input type="text" id="user"
                              name="myuser" required />
                </div>
                <div class="block">
                       <label for="password">Password</label> <input type="password" id="pin"
                              name="mypassword" required />
                </div>
                <div class="block">
                       <label for="file">ZIP File</label> <input type="file" id="file"
                              name="myfile" required />
                </div>
                <div>
                       <input type="submit" value="Upload" />
                </div>
         </form>
   </div>

</body>
</html>

我的实现如下。

public class MultipartUploader {

    private static final String CHARSET = "UTF-8";

    private static final String CRLF = "\r\n";

    public String httpUpload(String url, String filename, byte[] byteStream)
        throws MalformedURLException, IOException {

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        final String boundary = Strings.repeat("-", 15) + Long.toHexString(System.currentTimeMillis());

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        OutputStream directOutput = connection.getOutputStream();
        PrintWriter body = new PrintWriter(new OutputStreamWriter(directOutput, CHARSET), true);

        body.append(CRLF);
        addSimpleFormData("myuser", "myUserName", body, boundary);
        addSimpleFormData("mypassword", "mySecretPassword", body, boundary);
        addFileData("myfile", filename, byteStream, body, directOutput, boundary);
        addCloseDelimiter(body, boundary);

        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        String payload = CharStreams.toString(new InputStreamReader(connection.getInputStream()));
        return payload;
    }

    private static void addSimpleFormData(String paramName, String wert, PrintWriter body,
        final String boundary) {

        body.append(boundary).append(CRLF);
        body.append("Content-Disposition: form-data; name=\"" + paramName + "\"").append(CRLF);
        body.append("Content-Type: text/plain; charset=" + CHARSET).append(CRLF);
        body.append(CRLF);
        body.append(wert).append(CRLF);
        body.flush();
    }

    private static void addFileData(String paramName, String filename, byte[] byteStream, PrintWriter body,
        OutputStream directOutput, final String boundary) throws IOException {

        body.append(boundary).append(CRLF);
        body.append("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + filename + "\"")
            .append(CRLF);
        body.append("Content-Type: application/octed-stream").append(CRLF);
        body.append("Content-Transfer-Encoding: binary").append(CRLF);
        body.append(CRLF);
        body.flush();

        directOutput.write(byteStream);
        directOutput.flush();

        body.append(CRLF);
        body.flush();
    }

    private static void addCloseDelimiter(PrintWriter body, final String boundary) {

        body.append(boundary).append("--").append(CRLF);
        body.flush();
    }
}

服务器响应 200 OK。我的问题是,HTTP正文没有正确创建,因此我从服务器收到的响应说表单的不是所有字段都已设置。服务器没有说是哪个字段。
所以我的问题是,你是否看到这段代码有任何问题?我是否正确创建了多部分请求?
我还尝试使用以下命令使用cURL上传文件,并且它起作用了。
cURL -F "myuser=myUserName" -F "mypassword=mySecretPassword" -F "myfile=@/path/to/my/file.zip" "http://abcdef.gh:1234/path/to/uploader"

好的,表单中有哪些字段?你能展示一下服务器端吗? - Evan Knowles
1
@EvanKnowles 我刚刚更新了问题。 - Said Savci
1
@Devstr 如果可能的话,我本来会这样做的,但在我的情况下这不是一个选项。 - Said Savci
当我查看发送到服务器的HTTP正文时,我发现MIME部分头之间实际上没有换行符。这可能是什么原因?如您所见,我确实添加了换行符。或者它们只是编辑器没有显示出来。 - Said Savci
你可以使用 https://httpbin.org/ (/post) 进行调试。 - Devstr
显示剩余2条评论
2个回答

7

您的数据部分之间的边界在开头缺少额外的两个破折号:--

我通过捕获通过您的程序和curl发送到http://httpbin.org/post的请求,并使用diff工具进行比较,发现了这个问题。我使用Wireshark来捕获请求。

以下是如何解决此问题:

private static void addSimpleFormData(String paramName, String wert, PrintWriter body,
                                      final String boundary) {

    body.append("--").append(boundary).append(CRLF);
    body.append("Content-Disposition: form-data; name=\"" + paramName + "\"").append(CRLF);
    body.append("Content-Type: text/plain; charset=" + CHARSET).append(CRLF);
    body.append(CRLF);
    body.append(wert).append(CRLF);
    body.flush();
}

private static void addFileData(String paramName, String filename, byte[] byteStream, PrintWriter body,
                                OutputStream directOutput, final String boundary) throws IOException {

    body.append("--").append(boundary).append(CRLF);
    body.append("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + filename + "\"")
            .append(CRLF);
    body.append("Content-Type: application/octed-stream").append(CRLF);
    body.append("Content-Transfer-Encoding: binary").append(CRLF);
    body.append(CRLF);
    body.flush();

    directOutput.write(byteStream);
    directOutput.flush();

    body.append(CRLF);
    body.flush();
}

private static void addCloseDelimiter(PrintWriter body, final String boundary) {
    body.append("--").append(boundary).append("--").append(CRLF);
    body.flush();
}

注意在每个方法的开头加上额外的.append("--")


请查看https://gist.github.com/shtratos/8e9570a4a5591b2bcecd55ca60b3f24f以获取完整的可工作代码。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接