使用 HTTP POST 请求将文件从 Java 客户端上传到服务器时,很常见想要在文件中包含其他参数。这是一个简单而高效的解决方案,无需外部库:
利用 java.net.URLConnection 建立 HTTP 请求并将其设置为多部分表单数据,这是一种流行的编码格式,用于处理二进制和文本数据。这是一个包含附加参数 param 和文件 textFile 和 binaryFile 的示例:
<code class="java">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"); 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 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 boundary writer.append("--" + boundary + "--").append(CRLF).flush(); }</code>
设置请求后,您可以触发它并检索响应代码:
<code class="java">((HttpURLConnection) connection).getResponseCode();</code>
了解更多高级场景或简化流程,请考虑使用第三方库,例如 Apache Commons HttpComponents Client。
以上是如何使用Java的`URLConnection`上传文件和附加参数?的详细内容。更多信息请关注PHP中文网其他相关文章!