gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:17:09 27 4
gpt4 key购买 nike

我正在尝试实现一个 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"

最佳答案

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

我通过捕获对 http://httpbin.org/post 的请求发现了这一点通过您的程序和 curl 制作并通过 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完整的工作代码

关于用于上传文件的 Java HTTP 客户端 (multipart/form-data),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48944152/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com