Wrox Home  
Search P2P Archive for: Go

  Return to Index  

pro_java_server thread: Can a Java Client talk to Servlet


Message #1 by kpraveen@i... on Thu, 8 Feb 2001 06:20:57 -0000
found it, here is some code that does java client to servlet communication:
I got
it from chapter 
11 of professional java server programming. . The servlet that accepts this
request is nothing unusual, it doesnt care whether a browser or an applet,
or a client is
the consumer, it cant tell the difference.

try {
// first you must instantiate a URL object with the url of the
servlet.
URL url = new URL("http://localhost:8080/servlet/DbServlet");

// you then open the connection to the URL.
URLConnection uc = url.openConnection();

// set the connection to both output and input, cache off
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setUseCaches(false);

// the content type is set to URL encoded - in the original
application this was
// a url encoded sql string. I guess it is probably easier to put
together the
// sql query at the applet side rather than passing code values.
uc.setRequestProperty("Content-type", 
"application/x-www-form-urlencoded");

// open a stream to the connection object for writing to.
(dataoutput streams are
// for writing bytes so we cant send characters). Write the query
string to the // stream, then flush and close it. The connection is
still open at this point.
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());

// The output stage
dos.writeBytes(qry);
dos.flush();
dos.close();

// we now open a character reader for the return value from the
servlet. In this 
// case the servlet returned string values.
InputStreamReader in = new InputStreamReader(uc.getInputStream());

// read one character at a time until the end of the line. I'm
not sure why it 
// reads one at a time. Possibly to make sure that it doesnt lose
all the 
// information if the internet connection fails. then close the
output stream
// I suppose that the connection should be closed as well when
you are finished // with it, although this might be automatic. If
you are interested check the
// java docs for URLConnection.

int chr = in.read();
while (chr != -1) {
taResults.append(String.valueOf((char) chr));
chr = in.read(); 
}
in.close();

} catch(MalformedURLException e) {
taResults.setText(e.toString());
} catch(IOException e) {
taResults.setText(e.toString());
}
}

chanoch

  Return to Index