为了将带有附加参数的文件从 Java 客户端上传到 HTTP 服务器,让我们探索一下一个场景及其解决方案。
假设您想要将一个文件和一个名为“用户名”的参数传递到服务器。如何使用带有 multipart/form-data 编码的 POST 请求来实现此目的?
为了让事情简单明了,让我们避开第三方库并依赖 Java 的内置工具。
<code class="java">import java.io.File; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.util.Scanner; public class HttpFileUploadWithParameters { private static final String BOUNDARY = Long.toHexString(System.currentTimeMillis()); private static final String CRLF = "\r\n"; private static final String CHARSET = "UTF-8"; public static void main(String[] args) throws Exception { String url = "http://example.com/upload"; File file = new File("/path/to/file.txt"); String parameter = "value"; 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)) { // Write parameter writer.append("--" + BOUNDARY).append(CRLF); writer.append("Content-Disposition: form-data; name=\"parameter\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + CHARSET).append(CRLF); writer.append(CRLF).append(parameter).append(CRLF).flush(); // Write file writer.append("--" + BOUNDARY).append(CRLF); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append(CRLF); writer.append("Content-Type: application/octet-stream").append(CRLF); writer.append(CRLF).flush(); Files.copy(file.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // 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 = ((java.net.HttpURLConnection) connection).getResponseCode(); System.out.println(responseCode); // Should be 200 } }</code>
以上是如何在没有第三方库的情况下使用'multipart/form-data”编码从 Java 客户端上传带有附加参数的文件?的详细内容。更多信息请关注PHP中文网其他相关文章!