Java Reference
In-Depth Information
After the name line has been written, the Content-Type should be written. The
Java function guessContentTypeFromName is used to attempt to determine the
content type. This function works by looking at the extension and mapping well-known exten-
sions to their proper MIME type. If a MIME type cannot be found, then the MIME type of
application/octet-stream is used. This type indicates that the file is simply a
stream of binary data.
write("Content-Type: ");
String type = URLConnection.guessContentTypeFromName(file.get-
Name());
if (type == null)
type = "application/octet-stream";
writeln(type);
newline();
Once the content type has been written, it is time to write the file. The file is transferred
byte-by-byte. No data transformation takes place.
First, several variables are set up to transfer the file. A buffer is then created to hold
blocks of data. The variable nread tracks the amount of data being read.
byte[] buf = new byte[8192];
int nread;
Once the buffer is established, the file is opened and copied to the output stream.
InputStream in = new FileInputStream(file);
while ((nread = in.read(buf, 0, buf.length)) >= 0)
{
os.write(buf, 0, nread);
}
Once the file has been written, add a blank line.
newline();
}
These two overloaded versions of the add method allow you to add both files and regu-
lar fields.
Parse a Query String
The previous two methods we examined allow you to create a form response. The
parse method does the opposite. The parse function allows you to parse a name-value
pair string and extract values. A common use of this, is when your bot must examine a URL
returned by the web server, and extract variables from that URL.
To use this method, we must pass the parse function a string containing the name-
value pairs, and it will return them parsed as a Map object.
Search WWH ::




Custom Search