↑
Main Page
httpGet
function httpGet(sURL) {
var oURL = new java.net.URL(sURL);
//...
}
Note that when you use LiveConnect, you must furnish the complete name of the class, including the
package, to instantiate a Java object. After the URL is created, you open up an input stream and create a
reader to get the data back. The preferred way to do this is to create an
InputStreamReader
and then a
BufferedReader
based on it:
function httpGet(sURL) {
var oURL = new java.net.URL(sURL);
var oStream = oURL.openStream();
var oReader = new java.io.BufferedReader(new
java.io.InputStreamReader(oStream));
//...
}
With the buffered reader created, all that’s left to do is read the data back from the server. A buffered
reader gets data line-by-line, so you create a variable to build up the response into the full text. This
response text variable (named
sResponseText
) must start out as an empty string, not null, so that
string concatenation can be used to build the result:
function httpGet(sURL) {
var oURL = new java.net.URL(sURL);
var oStream = oURL.openStream();
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();
}
//...
}
Because the buffered reader returns lines, each line must be appended with a new line character to
ensure that it remains in the same form, as it should. The last steps are to close the reader and return
the response text:
function httpGet(sURL) {
var oURL = new java.net.URL(sURL);
var oStream = oURL.openStream();
499
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 499
Free JavaScript Editor
Ajax Editor
©
→