首先: 建立应用程序,限于技术的原因,利用j2se写了比较简单的应用程序,应用程序负责把要处理的数据,(如果都是针对于java,可以是对象,利用对象流)发送给web服务器对应的url/servlet,处理以后,返回响应的数据.
这个通讯的原理在页面上的理解就是利用了http协议,通过建立应用程序于servlet的httpurlconnection:
//建立连接
URL url= new URL("http://localhost/datareceiveservlet?userid=lhz&tel=1111111111&type=0&length=8");
URLConnection urlconn = (URLConnection)url.openConnection();
//设置连接属性
urlconn.setDoOutput(true);
urlconn.setUseCaches(false);
urlconn.setRequestProperty("Content-type","application/octest-stream");
urlconn.setRequestProperty("Content-length",""+buf.length());
//生成数据流
String buf ="aaaaaaaa";
DataOutputStream dataout=new DataOutputStream(urlconn.getOutputStream());
dataout.writeUTF(buf);
dataout.flush();
dataout.close();
//接受servlet的响应数据
DataInputStream in = new DataInputStream(urlconn.getInputStream());
String response = in.readUTF();
System.out.println("read from server :" + response);
in.close();
建立 DataReceiveServlet
public void dopost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
perform(request,response);
}
public void perform(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
int type=Integer.parseInt(request.getParameter("type").trim());
String userid=request.getParameter("userid").trim();
String tel=request.getParameter("tel").trim();
int typeindex= request.getQueryString().trim().indexOf("type");
DataInputStream in = new DataInputStream(request.getInputStream());
response.setContentType("application/octest-stream");
//type=2
if(type==2)
{
String queryString =request.getQueryString().trim().substring(typeindex+7);
Action1 action1 =new Action1(ds);
Action1.createMMS(queryString,in,userid,tel,type);
}else if(type==0 || type==1)//sms数据或ems
{
//调要Action
Action action =new Action(ds);
action.create (in,userid,tel,type);
}
//返回信息给客户端
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteout);
out.writeUTF("接受到数据");
out.flush();
byte buf[] = byteout.toByteArray();
response.setContentLength(buf.length);
ServletOutputStream servletout = response.getOutputStream();
servletout.write(buf);
servletout.close();
in.close();
return;
能发送的文件不仅仅是文本 ,可以是图片 ,声音 ,和其他文件 ,必须把所需要的文件生成字节数组 ,生成数据流再进行传输 .