I am new to Jersey. I have 2 things to know. 1. Send domain objects from client to server 2. Send domain Objects to client from server.
I want to send my custom Objects from client to server application. Since types of objects that are to be sent can be differ (it can be a domain object, File or image ), I supposed to convert those objects to stream and send to server. Also with the stream, I need to send send some parameters as well. Then I need to retrieve the stream in server and process it.
Once domain objects convert into stream, then they should be sent to the client as well.
I use Jersey 2.8 . Java 8 . Tomcate 6 . Here is how I tried to do it, but it fails(Might be a wrong approach)
Here is my client:
InputStream returnStrem = (InputStream)client.target("http://localhost:8080/TestJerseyProject")
.path("rest/save")
.request(new MediaType[] {MediaType.APPLICATION_OCTET_STREAM_TYPE})
.get(InputStream.class);
try {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(returnStrem));
Object o= ois.readObject();
System.out.println("Entity : "+o );
}catch(Exception e){
e.printStackTrace();
}finally {
returnStrem.close();
}
The server side code :
@Path("/cache")
public class ObjectCacheAction {
@GET
@Consumes("application/octet-stream")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response streamExample(InputStream is) {
try {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(is));
Object o= ois.readObject();
System.out.println("Entity : "+o );
is.close();
}catch(Exception e){
e.printStackTrace();
}finally {
}
StreamingOutput stream = new StreamingOutput() {
public void write(OutputStream os) throws IOException,
WebApplicationException {
try {
MyObj m=new MyObj();//My Domain Object
m.setName("sdfsdf");
ObjectOutputStream oos1 = new ObjectOutputStream(os);
oos1.writeObject(m);
oos1.flush();
oos1.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
return Response.ok(stream).build();
}
}
May be my approach is wrong. How ever, please let me know how I can I do this with working code sample. I tried over Internet, but most of them are Jersey 1.X.
JSON? I can see why you wouldn't want to use JSON if your object were large but you have to serialize them somehow so the overhead might not be that bad. You get the benefit of portability and built-in marshalling from Jersey to simply things.