在 Java 中使用附加参数将文件上传到 HTTP 服务器
将文件上传到 HTTP 服务器是许多应用程序的常见需求。但是,有时还需要随文件一起传递附加参数。这是一个允许您在不使用外部库的情况下发送文件和参数的解决方案:
java.net.URLConnection 和 Multipart/Form-Data
发送文件和参数,您将利用 java.net.URLConnection 并采用 multipart/form-data 编码。 Multipart/form-data 允许您在单个 HTTP 请求中混合二进制数据(文件)和字符数据(参数)。
示例代码:
String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" textFile.getName() "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" charset).append(CRLF);
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush();
writer.append(CRLF).flush();
// Send binary file.
writer.append("--" boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" binaryFile.getName() "\"").append(CRLF);
writer.append("Content-Type: " URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush();
writer.append(CRLF).flush();
// End of multipart/form-data.
writer.append("--" boundary "--").append(CRLF).flush();
}
// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode);
附加说明:
参考:
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3