Write a client class that communicates with the Restlet server to test for successful communication and to interact. In order to facilitate the use of other people, so, write a common method of encapsulation, but halfway through the release of some problems.
In the normal way, the sequence goes down like this:
Public Static voidMain (String args[]) {string URL= "Http://localhost:8888/hi"; Clientresource Clientresource=Newclientresource (URL); User User=NewUser (); User.setname ("ZZ"); User.setage ("12");Representation Representation=clientresource.post ((NewJacksonrepresentation<user>(user))); Jacksonrepresentation<User> jacksonrepresentation=NewJacksonrepresentation<user> (Representation,user.class); Try{User user1=Jacksonrepresentation.getobject (); System.out.println (User1.getname ()); System.out.println (User1.getage ()); } Catch(IOException e) {e.printstacktrace (); } }
So there is no problem, you can successfully get the data returned by the server, so on this basis, the restlet things to wrap up. Written in this way:
Public StaticObject getserverresponse (String url,object user) {Clientresource clientresource=Newclientresource (URL); Representation representation=clientresource.post ((NewJacksonrepresentation<object>(user))); Jacksonrepresentation<Object> jacksonrepresentation=NewJacksonrepresentation<object> (Representation,object.class); Object o=NULL; Try{o=Jacksonrepresentation.getobject (); } Catch(IOException e) {e.printstacktrace (); } returno; }
So in the main method, you can convert object to user. However, during the conversion process, an error is reported:
Exception in thread "main" Java.lang.ClassCastException:java.util.LinkedHashMap cannot is cast to test. User
Unable to convert Linkedhashmap to user, Linkedhashmap is not used in the code and should be the problem that occurs during the Restlet conversion process. Later tangled up, asked a more experienced colleagues, only to know the above conversion, and did not give a clear definition of the type of return, only converted to object, this is not possible.
After the transformation, the final wording is this:
Public Static<t, v> V get (String URL, T data, class<v>response) {Clientresource Clientresource=Newclientresource (URL); Representation representation=clientresource.post ((NewJacksonrepresentation<t>(data))); Jacksonrepresentation<V> jacksonrepresentation=NewJacksonrepresentation<v>(representation, response); Try { returnJacksonrepresentation.getobject (); } Catch(IOException e) {e.printstacktrace (); } return NULL; }
Thus, using generics, in this encapsulated method, the type of the returned data is specified so that no previous error occurs.
Java Generics and Restlet clients