用输入输出流实现往服务器端发送消息并接收返回的消息。
客户端StreamTest.java:
publicclassStreamTestimplementsController{
publicModelAndViewhandleRequest(HttpServletRequestreq,
HttpServletResponseres)throwsException{
URLurl=newURL("http://localhost:8088/Test/streamtestserver.do");
HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");//设置请求方式
con.setRequestProperty("Content-Type","application/stream");//设置请求类型
//con.setRequestProperty("Content-Length",Integer.toString(data.length()));
con.setDoOutput(true);//默认是false,将doOutput标志设置为true,指示应用程序要将数据写入URL连接。
con.setDoInput(true);//默认是true,将doInput标志设置为true,指示应用程序要从URL连接读取数据。
con.setUseCaches(false);//如果为true,则只要有条件就允许协议使用缓存。如果为false,则该协议始终必须获得此对象的新副本。
con.setInstanceFollowRedirects(true);
//con.connect();
System.out.println("StreamTest...................");
OutputStreamo=con.getOutputStream();
DataOutputStreamd=newDataOutputStream(o);
d.write("zy".getBytes());
//d.flush();
//d.close();
//con.disconnect();
BufferedReaderbf=newBufferedReader(newInputStreamReader(con.getInputStream()));
StringBuffersf=newStringBuffer();
Stringstr;
while((str=bf.readLine())!=null)
{
sf.append(str);
}
bf.close();
con.disconnect();
System.out.println("StreamTestStr="+sf.toString());
returnnull;
}
}
服务器端StreamTestServer.java
publicclassStreamTestServerimplementsController{
publicModelAndViewhandleRequest(HttpServletRequestreq,
HttpServletResponseres)throwsException{
BufferedReaderbf=newBufferedReader(req.getReader());
StringBuffersf=newStringBuffer();
Stringstr;
while((str=bf.readLine())!=null)
{
sf.append(str);
}
bf.close();
System.out.println("StreamTestServer="+sf.toString());
if(sf.toString().equals("zy")){
res.getWriter().write("123456");//(1)
}
returnnull;
}
}
输出结果为
StreamTest...................
StreamTestServer=zy
StreamTestStr=123456
Server端的(1)也可以改成returnnewModelAndView("test.jsp");
jsp中是要输出的内容,不过因为客户端读到的是源文件,所以要把jsp中无用的东西去掉,只写需要传回的信息