Java Reference
In-Depth Information
{
Map<String, String> map = FormUtility.parse(query);
return map.get("session");
} else
return null;
Once the session id has been obtained, the
search
function can be called.
Performing the Search
The
search
method submits the search form and reads the results from that search.
The session id must be attached to the URL that is posted to.
The
search
method begins by setting up several variables that will be needed. The
states or capitals returned from the search will be in an HTML list. So the starting and end-
ing tags, which in this case are
<ul>
and
</ul>
, are stored in the variables
listType
and
listTypeEnd
. Additionally, a
StringBuilder
, named
buffer
is created to
hold the HTML text as it is encountered. The
boolean
capture variable indicates if text is
currently being captured to the
StringBuilder
.
String listType = "ul";
String listTypeEnd = "/ul";
StringBuilder buffer = new StringBuilder();
boolean capture = false;
List<String> result = new ArrayList<String>();
The
FormUtility
class is designed to output to an
OutputStream
. For an
HTTP POST response, this will be fine. The three calls to the add method below setup the
different required name-value pairs for the form.
// Build the URL.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FormUtility form = new FormUtility(bos, null);
form.add("search", search);
form.add("type", type);
form.add("action", "Search");
form.complete();
A
URL
object is created for the form's location plus the session ID. The rest of this proce-
dure is very similar to the list parsing example from recipes 7.1 and 7.2 in Chapter 7.
URL url = new URL(
"http://www.httprecipes.com/1/8/menunc.php?session="
+ session);
URLConnection http = url.openConnection();
http.setDoOutput(true);
OutputStream os = http.getOutputStream();