再給你一份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();
}
}
|