18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Client-Server Communication<br />

function httpGet(sURL) {<br />

var oURL = new java.net.URL(sURL);<br />

}<br />

//...<br />

Note that when you use LiveConnect, you must furnish the complete name of the class, including the<br />

package, to instantiate a Java object. After the URL is created, you open up an input stream and create a<br />

reader to get the data back. The preferred way to do this is to create an InputStreamReader and then a<br />

BufferedReader based on it:<br />

function httpGet(sURL) {<br />

var oURL = new java.net.URL(sURL);<br />

var oStream = oURL.openStream();<br />

var oReader = new java.io.BufferedReader(new<br />

java.io.InputStreamReader(oStream));<br />

}<br />

//...<br />

With the buffered reader created, all that’s left to do is read the data back from the server. A buffered<br />

reader gets data line-by-line, so you create a variable to build up the response into the full text. This<br />

response text variable (named sResponseText) must start out as an empty string, not null, so that<br />

string concatenation can be used to build the result:<br />

function httpGet(sURL) {<br />

var oURL = new java.net.URL(sURL);<br />

var oStream = oURL.openStream();<br />

var oReader = new java.io.BufferedReader(new<br />

java.io.InputStreamReader(oStream));<br />

var sResponseText = “”;<br />

var sLine = oReader.readLine();<br />

while (sLine != null) {<br />

sResponseText += sLine + “\n”;<br />

sLine = oReader.readLine();<br />

}<br />

}<br />

//...<br />

Because the buffered reader returns lines, each line must be appended with a new line character to<br />

ensure that it remains in the same form, as it should. The last steps are to close the reader and return<br />

the response text:<br />

function httpGet(sURL) {<br />

var oURL = new java.net.URL(sURL);<br />

var oStream = oURL.openStream();<br />

499

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!