p> Applet与Java Servlet可以通过HTTP协议的GET和POST进行交互,Applet必须打开一个到指定的servlet
URL的连接。一旦建立了此连接,applet就可以从servlet得到一个output stream或者一个input
stream。 applet可以通过发送一个GET或者一个POST方法将数据发送到servlet。 一
GET方法 使用GET方法发送数据到servlet,applet必须将name/value
配对参数翻译成为实际的URL字符串。例如要发送name/value配对信息"LastName=Jones",servlet
URL如下: http://www.foo.com/servlet/TestServlet?LastName=Jones 如果还有另外的配对信息,则用一个’&’符号将它们连接。方法如下: http://www.foo.com/servlet/TestServlet?LastName=Jones&FirstName=Joe 在应用中,必须翻译每一个按name/value配对的信息。为发送一个方法GET方法到servlet,applet用类java.net.URLConnection来实现。下面的代码片段将实现:
String location =
"http://www.foo.com/servlet/TestServlet?LastName=Jones"; URL testServlet =
new URL(location); URLConnection servletConnection =
testServlet.openConnection(); inputStreamFromServlet =
servletConnection.getInputStream(); //
从servlet读input。 一旦applet建立了一个到URL的连接,这时访问了来自servlet 的input
stream。applet可以读这个input stream从而处理此数据。依赖servlet返回此数据的类型和格式。如果servlet
正返回定制的信息,需要创建一个定制的消息传输协议来实现applet 和
servlet通信(交互)。 二、POST方法 使用POST方法发送数据到servlet,必须通知URL连接output
stream发送数据。方法POST是很强大的,因为它可以发送任何形式的数据(诸如纯文本,二进制码之类)。您需要做的只是在HTTP
请求header中设置满意的类型。但是,此servlet必须可以处理由applet发送的此类型的数据。 下面的代码片段显示了如何发送方法POST到一个servlet
URL。 // 连接servlet String location =
"http://www.foo.com/servlet/TestServlet"; URL testServlet = new URL(
servletLocation ); URLConnection servletConnection =
testServlet.openConnection();
// 通知此连接我们将要发送output并且要接收input servletConnection.setDoInput(true);
servletConnection.setDoOutput(true); < /不能使用URL
connection的缓存。 servletConnection.setUseCaches
(false); servletConnection.setDefaultUseCaches (false);
// 指定我们将要发送的数据内容的类型为binary数据 servletConnection.setRequestProperty ("Content-Type",
"$#@60;insert favorite mime
type$#@62;");
// 从servlet上取得input和output streams . . .
// 将您的数据发送到servlet . . .
|