再给你一份Applet与servlet的示例程序:
String m_hostName=getCodeBase().getHost();
String m_servletName= "http:// "+m_hostName+ ":8080/birdWeb3S/vehicleservlet ";//设置Servlet的路径
URL servletURL=new URL(m_servletName);
HttpSendMessage m_message=new HttpSendMessage(servletURL);//初始化中间层
//Applet中的示范程序
public void AlarmSet(String strAlarmID,String strVehicleVin)
{
try
{
Properties pts=new Properties();
pts.put( "AlarmSet ", "ok ");
pts.put( "AlarmID ",strAlarmID);
pts.put( "VehicleVin ",strVehicleVin);
InputStream in=m_message.sendGetMessage(pts);//采用DoGet传递参数
InputStream in=m_message.sendPostMessage(pts);//采用DoPost传递参数
DataInputStream out=new DataInputStream(in);//接收Servlet返回的数据流
}
catch(IOException ex)
{
}
}
//中间层用于Applet与Servlet之间的通讯
class HttpSendMessage extends Object{
URL Servlet=null;
String args=null;
public HttpSendMessage(URL Servlet)//中间层的构造函数
{
this.Servlet=Servlet;
}
public InputStream sendGetMessage() throws IOException//DoGet无参数传递
{
return sendGetMessage(null);
}
public InputStream sendGetMessage(Properties args) throws IOException//DoGet参数传递
{
String argString= " ";
if(args!=null)
{
argString= "? "+toEncodedString(args);//转换参数传递类型便于Sevlet的DoGet接收参数及参数解码
}
URL url=new URL(Servlet.toExternalForm()+argString);
URLConnection con=url.openConnection();
con.setUseCaches(false);
InputStream in=con.getInputStream();
return in;
}
public InputStream sendPostMessage() throws IOException//DoPost无参数传递
{
return sendPostMessage(null);
}
public InputStream sendPostMessage(Properties args) throws IOException//DoPost参数传递
{
String argString= " ";
if(args!=null)
{
argString= "? "+toEncodedString(args);
}
URL url=new URL(Servlet.toExternalForm()+argString);
URLConnection con=url.openConnection();
con.setDoInput(true);//用于接收数据流,可以不用。
con.setDoOutput(true);//用于传递数据流
con.setUseCaches(false);
con.setRequestProperty( "Content-Type ", "application/x-www-form-urlencoded ");//设置为DoPost传递参数
DataOutputStream out=new DataOutputStream(con.getOutputStream());
//out.writeBytes(argString);//在不传递文件流时不用
//out.flush();
out.close();
InputStream in=con.getInputStream();
return in;
}
//参数解码
private String toEncodedString(Properties args)
{
StringBuffer buf=new StringBuffer();
Enumeration names=args.propertyNames();
while(names.hasMoreElements())
{
String name=(String)names.nextElement();
String value=args.getProperty(name);
buf.append(URLEncoder.encode(name)+ "= "+URLEncoder.encode(value));
if(names.hasMoreElements())
{
buf.append( "& ");
}
}
return buf.toString();
}
}
|