When using HTTP POST requests to upload files from a Java client to a server, it's common to want to include additional parameters along with the files. Here's a simple and efficient solution without the need for external libraries:
Utilize java.net.URLConnection to establish the HTTP request and set it up for multi-part form data, a popular encoding format for handling both binary and text data. Here's an example that includes additional parameter param and files textFile and 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>
After setting up the request, you can fire it and retrieve the response code:
<code class="java">((HttpURLConnection) connection).getResponseCode();</code>
For more advanced scenarios or to simplify the process, consider using third-party libraries like Apache Commons HttpComponents Client.
The above is the detailed content of How to Upload Files and Additional Parameters with Java\'s `URLConnection`?. For more information, please follow other related articles on the PHP Chinese website!