public class MultipartRequestSender {
private static final String BOUNDARY = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
public static void sendMultipartRequest(String requestURL, File xmlFile) throws IOException {
URL url = new URL(requestURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true); // Indicates POST method
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
try (OutputStream outputStream = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
FileInputStream fileInputStream = new FileInputStream(xmlFile)) {
// Send XML file.
writer.append("--" + BOUNDARY).append("rn");
writer.append("Content-Disposition: form-data; name="xmlFile"; filename="" + xmlFile.getName() + """).append("rn");
writer.append("Content-Type: text/xml; charset=UTF-8").append("rn");
writer.append("rn").flush();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush(); // Important before continuing with writer!
writer.append("rn").flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + BOUNDARY + "--").append("rn").flush();
}
// Check server's response.
System.out.println("Response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
connection.disconnect();
}
}
see the xml loaded in the java. Step-by-Step Guide to Sending Multipart Form Data with XML in Java
-
Add Required Libraries:
- Java doesn’t provide built-in support for creating multipart form data easily, so it’s common to use
org.apache.http
libraries, which greatly simplify the process. However, if you want to stick withHttpsURLConnection
, you will need to manually construct the multipart body.
- Java doesn’t provide built-in support for creating multipart form data easily, so it’s common to use
-
Prepare Your Java Environment:
- If you choose to use Apache libraries, you can add them via Maven. If not, ensure your Java environment is set up to compile and run
HttpsURLConnection
code.
- If you choose to use Apache libraries, you can add them via Maven. If not, ensure your Java environment is set up to compile and run
-
Java Method Using
HttpsURLConnection
: Here is a simple Java method that constructs and sends a POST request with multipart/form-data containing an XML file:
New contributor
DEV Fusion is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.