簡體   English   中英

通過HTTP序列化轉換對象的正確方法

[英]Serializing over HTTP correct way to convert object

我正在嘗試序列化對象並通過HTTP發送它。 我正在使用一些教程,因為大多數教程都是關於套接字的,但是我不能為此使用套接字,也不能使用在本地存儲的文件。

這是測試類Employee:

public class Employee implements java.io.Serializable {
        public String name;
        public String address;
        public transient int SSN;
        public int number;

        public void mailCheck() {
            System.out.println("Mailing a check to " + name + " " + address);
        }

} 

客戶端:

public class SerializeAndSend {

    public static void main(String args[]){

          one.Employee e = new one.Employee();
          e.name = "Reyan Ali";
          e.address = "Phokka Kuan, Ambehta Peer";
          e.SSN = 11122333;
          e.number = 101;

          sendObject(e);

    }

    public static Object sendObject(Object obj) {
        URLConnection conn = null;
        Object reply = null;
        try {

            // open URL connection
            URL url = new URL("///myURL///");
            conn = url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            // send object
            ObjectOutputStream objOut = new ObjectOutputStream(conn.getOutputStream());
            objOut.writeObject(obj);
            objOut.flush();
            objOut.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        // recieve reply
        try {
            ObjectInputStream objIn = new ObjectInputStream(conn.getInputStream());
            reply = objIn.readObject();
            objIn.close();
        } catch (Exception ex) {
            // it is ok if we get an exception here
            // that means that there is no object being returned
            System.out.println("No Object Returned");
            if (!(ex instanceof EOFException))
                ex.printStackTrace();
                System.err.println("*");
        }
        return reply;
    }

}

我認為那是正確的。 但是我被困在服務器端,我在服務器端也有employee類:

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    Object obj;
    ObjectInputStream objIn = new ObjectInputStream(req.getInputStream()); 

    try {
        obj = objIn.readObject();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Employee e = obj;

}

如何將此對象變回員工類對象?

任何幫助表示贊賞!

只是打字。

Employee emp = (Employee)objIn.readObject();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM