Main Page

Performing a POST request

var oReader = new java.io.BufferedReader(new
java.io.InputStreamReader(oStream));
var sResponseText = “”;
var sLine = oReader.readLine();
while (sLine != null) {
sResponseText += sLine + “\n”;
sLine = oReader.readLine();
}
oReader.close();
return sResponseText;
}
Now this function can be used to send a GET request using the same
addURLParam()
function defined
earlier:
var sURL = “http://www.somwhere.com/page.php”;
sURL = addURLParam(sURL, “name”, “Nicholas”);
sURL = addURLParam(sURL, “book”, “Professional JavaScript”);
var sData = httpGet(sURL);
Unfortunately, you don’t get all the same information, such as status, when using LiveConnect. Also,
this function creates a synchronous call without the option of creating an asynchronous one. But the
advantage is that this works in Netscape Navigator 4.x and most versions of Opera, as well as any other
browser that supports LiveConnect.
Performing a POST request
As discussed earlier, POST requests are slightly different from GET requests in their format and behav-
ior. However, it’s possible to send a POST request just as easily as a GET request using LiveConnect. To
start, you provide a URL and a parameters string (using
addPostParam()
from earlier in the chapter).
Then, you create another
java.net.URL
instance. Unlike last time, this code uses a
Connection
object
to facilitate the request:
function httpPost(sURL, sParams) {
var oURL = new java.net.URL(sURL);
var oConnection = oURL.openConnection();
//...
}
Next, you must determine the settings on the connection. Because a POST request is considered
bi-directional, the connection must be set up to accept input and output by using the
setDoInput()
Unlike the XML HTTP request object, LiveConnect requires you to enter the com-
plete URL for the request, starting with
http://
. This is because the Java objects
don’t have any sort of context for resolving relative URLs.
500
Chapter 16
19_579088 ch16.qxd 3/28/05 11:42 AM Page 500


JavaScript EditorFree JavaScript Editor     Ajax Editor


©