httpServlet 列子

阅读更多
向servlet发送xml的一个例子2010年11月09日 星期二 下午 03:17简单写了一个,只是验证一下数据流互相传送,具体功能可以自己加

test.java 客户端:读取1.xml文件发送给DataServer(servlet),读取servlet返回的内容
DataServer.java 服务器servlet:读取test发送的xml内容,把内容再返回给客户端

-----------------


/**
* Created by IntelliJ IDEA.
* User: dev
* Date: 2004-3-9
* Time: 12:43:44
* 客户端,发送xml
*/
import java.io.*;
import java.net.*;
public class test{
    public static void main(String[] args) throws Exception{

        /*初始化*/
        java.net.URL url = new java.net.URL("http://localhost:8080/servlet/DataServer");
        java.net.URLConnection con = url.openConnection();
         con.setUseCaches(false);
         con.setDoOutput(true);
         con.setDoInput(true);
        /*缓存*/
        BufferedReader fin = new BufferedReader(new FileReader("E:\\1.xml"));
        StringBuffer stringbuffer = new StringBuffer();
        char ac[] = new char[8192];
        int i;
        while ((i = fin.read(ac)) > 0)
        stringbuffer.append(ac, 0, i);
         fin.close();
        /*发送*/
        DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
         dataOut.writeUTF(stringbuffer.toString());
         dataOut.flush();
         dataOut.close();
        /*获取服务器端返回信息*/
        DataInputStream in =new DataInputStream(con.getInputStream());
        String stringValue = in.readUTF();
        in.close();
        System.out.println(stringValue);
    }
}


-------------------------

/**
* Created by IntelliJ IDEA.
* User: dev
* Date: 2004-3-9
* Time: 12:44:41
* 服务器servlet,客户端数据,返回信息
*/

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class DataServer extends HttpServlet {
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*读取数据*/
        DataInputStream in = new DataInputStream(req.getInputStream());
        String stringValue = in.readUTF();
        /*返回数据*/
        DataOutputStream dataOut = new DataOutputStream(resp.getOutputStream());
         dataOut.writeUTF(stringValue);
         dataOut.flush();
         dataOut.close();
    }
}



你可能感兴趣的:(httpServlet 列子)