HTTP Server File Uploads Using Java
Introduction
This article discusses uploading files to an HTTP server from a Java client. We aim to provide a simple and free solution that combines parameters and files within a POST request.
Multipart/Form-Data Encoding
For mixed POST content (binary and character data), multipart/form-data encoding is typically used. The data is divided into sections, each with its own header and body.
Java Solution
The following code demonstrates how to upload files and parameters using a direct HTTP connection without third-party libraries:
<code class="java">// Parameters String url = "http://example.com/upload"; String param = "value"; // File paths File textFile = new File("/path/to/file.txt"); File binaryFile = new File("/path/to/file.bin"); // Generate unique boundary value String boundary = Long.toHexString(System.currentTimeMillis()); // Create connection URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // OutputStream for writing data 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=\"param\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF).append(param).append(CRLF).flush(); // Write 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); // Ensure file is saved using this charset writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); writer.append(CRLF).flush(); // Write 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 multipart/form-data writer.append("--" + boundary + "--").append(CRLF).flush(); } // Get HTTP response code int responseCode = ((HttpURLConnection) connection).getResponseCode(); System.out.println(responseCode);</code>
Additional Notes
See Also
The above is the detailed content of How can I upload files and parameters to an HTTP server using pure Java without relying on third-party libraries?. For more information, please follow other related articles on the PHP Chinese website!