通过HTTP序列化转换对象的正确方法 [英] Serializing over HTTP correct way to convert object
本文介绍了通过HTTP序列化转换对象的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试序列化对象并通过HTTP发送它.我正在使用一些教程,因为大多数教程都是关于套接字的,但是我不能为此使用套接字,也不能使用在本地存储的文件.
I'm trying to serialize an object and send it over HTTP. I'm using a few tutorials as most deal with sockets but I can't use sockets for this, or with a file been stored locally.
这里是测试类Employee:
Here is the test class 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类:
I think thats correct. But I'm stuck on the server end, I have the employee class on the server side too:
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;
}
如何将此对象变回员工类对象?
How do I turn this object back into an employee class object?
任何帮助表示赞赏!
推荐答案
只需打字.
Employee emp = (Employee)objIn.readObject();
这篇关于通过HTTP序列化转换对象的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文