Java Reference
In-Depth Information
+ boundary);
An
OutputStream
object is obtained and we construct a new
FormUtility
object. Notice that a boundary is specified on the constructor to the
FormUtility
ob-
ject. This tells the
FormUtility
object that this is going to be a multipart response.
Additionally, the user id and password are added to the form. The names “uid” and “pwd”
are the names of the
<input>
tags that the user would normally enter their user id and
password into.
OutputStream os = http.getOutputStream();
// Construct a form.
FormUtility form = new FormUtility(os, boundary);
form.add("uid", uid);
form.add("pwd", pwd);
Next, the actual file is added to the form. This version of the
add
method of the
FormUtility
class takes care of all that is necessary to transmit the file. Finally, the
complete
method is called to complete building the form.
form.add("uploadedfile", file);
form.complete();
Next, the
InputStream
is obtained and the request is transmitted. The
InputStream
object is immediately closed; we do not care about the response from the
upload page.
// Perform the upload.
InputStream is = http.getInputStream();
is.close();
This recipe can be adapted to any case where you need to upload a file. The
FormUtility
class, used by this recipe, is a short utility class that was introduced ear-
lier in this chapter.
Summary
Forms are a very common part of many web sites. Most bot programs will have to deal
with forms. Forms can be transmitted to the web server in three ways: HTTP
GET
, HTTP
POST
and multipart
POST
.
A form can be sent back to the web server using the HTTP
GET
method. HTTP
GET
places all of the name-value pairs from the form's data onto the URL. When a web site uses
HTTP
GET
for a form, the user can see all of their input on the URL line of the browser.
A form can also be sent back to the web server using the HTTP
POST
method. HTTP
POST
sends the data as part of the HTTP packet, and it is not visible to the user. Because
the data does not all need to fit onto a URL, much larger amounts of data can be sent with
HTTP
POST
.