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);
// 指定我们将要发送的数据内容的类型为binary数据
servletConnection.setRequestProperty
("Content-Type", "$#@60;insert favorite mime type$#@62;");
// 从servlet上取得input和output streams
. . .
// 将您的数据发送到servlet
. . .