Java Reference
In-Depth Information
String uid = "";
String pwd = "";
String filename = "";
if (args.length < 3)
{
System.out.println("Usage:");
System.out.println(
"java FormUpload [User ID] [Password] [File to upload]");
} else
{
uid = args[0];
pwd = args[1];
filename = args[2];
FormUpload upload = new FormUpload();
upload.upload(uid, pwd, new File(filename));
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Most of the work done by this recipe is done inside of the FormUtility class. If you
would like to review how any of the methods and functions used in this recipe work, review
the section “Multipart Post”, from earlier in this chapter.
This recipe starts out by creating a boundary. The boundary is just a random string of
characters that is used to separate the different parts of the multipart response.
// Get the boundary used for the multipart upload.
String boundary = FormUtility.getBoundary();
A connection is opened to the URL that will receive the multipart response.
URLConnection http = (new URL("http://www.httprecipes.com/1/7/up-
loader.php"))
.openConnection();
Because this is going to be an HTTP POST we set the “do output” option to true. We also
construct the Content-Type header to specify that this will be a multipart response.
The boundary is specified inside of the Content-Type header.
http.setDoOutput(true);
// Specify that we will use a multipart form.
http.setRequestProperty("Content-Type", "multipart/form-data;
boundary="
Search WWH ::




Custom Search