Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

multipart form-data posts via http(s) connection without browser

843840May 2 2002 — edited Jan 29 2003
/**
* General solution to POST of multipart/form-data
* Essentially form fields with included attachments/uploads
*
* Add/Remove conetn dispositon and boundary sections as necessary
* Inlcudes exampels for form fileds , binary and text data file uploads
*
* I have seen hundreds of postings regarding this general question
* of uploads, this client includes examples of the key points to
* being successfull at uploading multipart form-data.
* Add and or remove the construct below as necessary
* Bascially:
*
* Open Boundary
* contents dispositions
* Close Boundary
*
*
-----------------------------7d01ecf406a6
Content-Disposition: form-data; name="formField1"

value_of_field1
-----------------------------7d01ecf406a6
Content-Disposition: form-data; name="formField2"

value_of_field2
-----------------------------7d01ecf406a6
Content-Disposition: form-data; name="formField3"

value_of_field3
-----------------------------7d01ecf406a6
Content-Disposition: form-data; name="zipFileAttached"; filename="theZipFile"
Content-Type: application/x-zip-compressed

the binary data goes here
-----------------------------7d01ecf406a6
Content-Disposition: form-data; name="textFileAttached"; filename="theTextFile"
Content-Type: plain/text

the text data goes here
-----------------------------7d01ecf406a6--
*
* theUrlConnection.setRequestProperty( "Content-Type", "multipart/form-data; boundary=" + boundary );
* streamSend.append("Content-Disposition: form-data; name=\"formField\"\r\n");
* streamSend.append("\r\n");
* streamSend.append("value_of_field\r\n");
* streamSend.append("--" + boundary + "\r\n");
* streamSend.append("Content-Disposition: form-data; name=\"nextField\"\r\n");
* streamSend.append("\r\n");
* streamSend.append("value_of_next_field\r\n");
* streamSend.append("--" + boundary + "--");
*
*
*
* Helpful url: http://www.vivtek.com/rfc1867.html
* url: http://www.ietf.org/rfc/rfc1867.txt
*/
import java.net.*;
import java.io.*;
import javax.net.*;
import com.sun.net.ssl.*;
import java.util.*;
import java.text.*;
import java.security.*;

/**
* POST a multipart form-data http stream to servlet
*/
public class HttpMultiPartPost {
public static void main(String[] args) throws Exception {
System.out.println("USAGE: java URLReaderWithOptions " +
" [-h proxyhost]"+
" [-p proxyport]"+
" [-k protocolhandlerpkgs] " +
" [-c ciphersarray]" +
" -u \"The base url\"");

// initialize system properties or command line parameters
// The default destination url "https://some.where.com"
String cmdDestUrl = new String("");

char option = 'z'; // Used to delimit,init the parameter parse loop
for (int i = 0; i < args.length; i++) {
if (option != 'z' && option != 'w') {
System.out.println("-"+option+" "+args);
}
switch(option) {
case 'h': // The Proxy Host to be utilised
System.setProperty("https.proxyHost", args[i]);
option = 'z'; // Reset option for next iteration
break;
case 'p': // The Proxy Port to be utilised
System.setProperty("https.proxyPort", args[i]);
option = 'z'; // Reset option for next iteration
break;
case 'k': // https Handler package to be utilised
System.setProperty("java.protocol.handler.pkgs", args[i]);
option = 'z'; // Reset option for next iteration
break;
case 'c': // The cipher "CERTS" to be utilized
System.setProperty("https.cipherSuites", args[i]);
option = 'z'; // Reset option for next iteration
case 'u': // The base url to connect to
cmdDestUrl = args[i];
option = 'z'; // Reset option for next iteration
break;
default:
// get the next option
if (args[i].startsWith("-")) {
option = args[i].charAt(1);
}
} // switch(option)
} // for (int i = 0; i < args.length; i++)

// Required for ssl support and avoiding error:
// "unknown protocol: https" exception
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

/*

- Connect to Servlet and send

NAME="formField1" VALUE="value_of_field1"
NAME="formField2" VALUE="value_of_field2"
NAME="formField3" VALUE="value_of_field3"
NAME="zipFileAttached"
NAME="textFileAttached"

*/

URL destUrl = new URL("https://some.where.com/servlet/MailboxServlet");

// Prepare the connection for recieving the form
URLConnection theUrlConnection = destUrl.openConnection();
theUrlConnection.setDoOutput(true);
theUrlConnection.setDoInput(true);
theUrlConnection.setUseCaches(false);

// Multi-Part delimiter
String boundary="--7d021a37605f0";
theUrlConnection.setRequestProperty( "Content-Type", "multipart/form-data; boundary=" + boundary );

System.out.println("Before DataOutputStream");
DataOutputStream postFormFile = new DataOutputStream(theUrlConnection.getOutputStream());

// Buffer used to build stream of multi-part form field
StringBuffer streamSend = new StringBuffer();

// Each form field is sent within a boundary delimeter
// Each file is also sent within a boundary delimeter

// Start form fields boundary section
streamSend.append("--" + boundary + "\r\n");

// <input TYPE="HIDDEN" NAME="formField1" VALUE="value_of_field1">
streamSend.append("Content-Disposition: form-data; name=\"formField1\"\r\n");
streamSend.append("\r\n");
streamSend.append("value_of_field1\r\n");
streamSend.append("--" + boundary + "\r\n");

// <input TYPE="radio" NAME="formField2" VALUE="value_of_field2">
streamSend.append("Content-Disposition: form-data; name=\"formField2\"\r\n");
streamSend.append("\r\n");
streamSend.append("value_of_field2\r\n");
streamSend.append("--" + boundary + "\r\n");

// <select NAME="formField3" VALUE="value_of_field3">
streamSend.append("Content-Disposition: form-data; name=\"formField3\"\r\n");
streamSend.append("\r\n");
streamSend.append("value_of_field3\r\n");
streamSend.append("--" + boundary + "\r\n");

// End form fields boundary section

// Begin attachments/uploads or FILE portions of multipart form-data stream
// <input TYPE="FILE" NAME="zipFileAttached" VALUE="theZipfile">
streamSend.append("Content-Disposition: form-data;name=\"zipFileAttached\"; filename=\"theZipFile\"\r\n");
streamSend.append("Content-Type: application/x-zip-compressed\r\n");
streamSend.append("\r\n");
postFormFile.write(streamSend.toString().getBytes());
System.out.println("Data Stream\n"+streamSend.toString());

// Ok were ready for the binary "zip" data stream
System.out.println("Before zip data Send");
// Read/Write zip File as bytes
try {
FileInputStream uploadFileReader = new FileInputStream("c:\\path\\to\\the\\zipfile.zip");
int numBytesToRead=1024;
int availableBytesToRead;
availableBytesToRead=uploadFileReader.available();
System.out.println("size of file: " + availableBytesToRead);
while ((availableBytesToRead=uploadFileReader.available()) > 0) {
byte[] bufferBytesRead;
// Adjust size of buffered bytes if necessary
bufferBytesRead = availableBytesToRead >= numBytesToRead?
new byte[numBytesToRead]:
new byte[availableBytesToRead];
// Trap end of file condition
int numberOfBytesRead = uploadFileReader.read(bufferBytesRead);
// Did we reach end of file
if (numberOfBytesRead == -1) break;
// Write current buffered bytes to servlet
postFormFile.write(bufferBytesRead);
} // Iterate through contents of file
} catch (IOException e) {
e.printStackTrace(System.out);
}
streamSend = new StringBuffer();
streamSend.append("--" + boundary + "\r\n");
postFormFile.write(streamSend.toString().getBytes());
System.out.println("After zip data Send");
// Ok done sending zip file data stream


// plain text attachments or FILE portions of multipart form-data stream
// <input TYPE="FILE" NAME="textFileAttached" VALUE="theTextfile">
streamSend = new StringBuffer();
streamSend.append("Content-Disposition: form-data;name=\"textFileAttached\"; filename=\"theTextFile\"\r\n");
streamSend.append("Content-Type: text/plain\r\n");
streamSend.append("\r\n");
postFormFile.write(streamSend.toString().getBytes());
System.out.println("Data Stream\n"+streamSend.toString());

// Ok were ready for the binary "zip" data stream
System.out.println("Before text data Send");
// Read/Write zip File as bytes
try {
FileInputStream uploadFileReader = new FileInputStream("c:\\path\\to\\the\textFile.txt");
int numBytesToRead=1024;
int availableBytesToRead;
availableBytesToRead=uploadFileReader.available();
System.out.println("size of file: " + availableBytesToRead);
while ((availableBytesToRead=uploadFileReader.available()) > 0) {
byte[] bufferBytesRead;
// Adjust size of buffered bytes if necessary
bufferBytesRead = availableBytesToRead >= numBytesToRead?
new byte[numBytesToRead]:
new byte[availableBytesToRead];
// Trap end of file condition
int numberOfBytesRead = uploadFileReader.read(bufferBytesRead);
// Did we reach end of file
if (numberOfBytesRead == -1) break;
// Write current buffered bytes to servlet
postFormFile.write(bufferBytesRead);
} // Iterate through contents of file
} catch (IOException e) {
e.printStackTrace(System.out);
}
System.out.println("After text data Send");
// Ok done sending zip file data stream

// Terminate file multipart form-data POST boundary's
streamSend = new StringBuffer();
streamSend.append("--" + boundary + "--\r\n");
postFormFile.write(streamSend.toString().getBytes());
System.out.println("Data Stream\n"+streamSend.toString());
// close/cleanup the https output stream
postFormFile.flush();
postFormFile.close();

// Parse results to ensure file was sent ok."
// Expecting: "Some sort of html response/confirmation"
// Read response from File Upload "Send" post
// Initialize the input stream to be read from
InputStream responseFromDestUrl = theUrlConnection.getInputStream();
// Build up respnse into a buffer
StringBuffer thisResponsePage = new StringBuffer();
byte[] respBuffer = new byte[4096];
// The number of bytes read
int bytesRead=0;
// Iterate to build up response from the request using logonUrl
while ((bytesRead = responseFromDestUrl.read (respBuffer)) >= 0) {
thisResponsePage.append(new String(respBuffer).trim());
}
responseFromDestUrl.close(); // Close response stream
System.out.println(thisResponsePage.toString());

// Close the http response page stream
responseFromDestUrl.close();

System.out.println("After https stream close");

System.out.println ("HttpMultiPartPost Done.");
} // public static void main(String[] args) throws Exception
} // public class HttpMultiPartPost
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 26 2003
Added on May 2 2002
3 comments
640 views