Home  >  Article  >  Java  >  How to upload files and additional parameters to an HTTP server using java.net.URLConnection?

How to upload files and additional parameters to an HTTP server using java.net.URLConnection?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 03:02:30181browse

How to upload files and additional parameters to an HTTP server using java.net.URLConnection?

Uploading Files to an HTTP Server with Additional Parameters in Java

Uploading files to an HTTP server is a common necessity for many applications. However, sometimes it is also necessary to pass additional parameters along with the files. Here's a solution that allows you to send both files and parameters without using external libraries:

java.net.URLConnection and Multipart/Form-Data

To send files and parameters, you'll utilize java.net.URLConnection and employ multipart/form-data encoding. Multipart/form-data allows you to mix binary data (files) and character data (parameters) in a single HTTP request.

Example Code:

<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");
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); </code>

Additional Notes:

  • Ensure to provide a unique boundary value for each multipart request.
  • Files must be in the charset specified when sending the Content-Type header.
  • Apache Commons HttpComponents Client can streamline the process further, but it's not necessary.

Reference:

  • [Using java.net.URLConnection to fire and handle HTTP requests](https://docs.oracle.com/javase/tutorial/networking/urls/creating-urls.html)

The above is the detailed content of How to upload files and additional parameters to an HTTP server using java.net.URLConnection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn