Client transfer options

I am using the RESTful web service. In this web service, I have to pass the bean that I want to save as a parameter.

Here is the server code:

@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Unidade inserir(Unidade unidade){ Session s = ConnectDb.getSession(); try { s.getTransaction().begin(); s.save(unidade); s.getTransaction().commit(); return unidade; } catch (Exception e) { e.printStackTrace(); s.getTransaction().rollback(); return null; } finally { s.close(); } } 

I have the following code in the client:

 ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource webResource = client.resource("http://localhost:8080/RestauranteWeb/rest/unidades/7"); Builder builder = webResource.accept(MediaType.APPLICATION_JSON); GenericType<Unidade> genericType = new GenericType<Unidade>() {}; Unidade u = new Unidade(); u.setUnidSigla("KG"); //How to pass this bean as parameter? Unidade response = builder.post(genericType); System.out.println(response); 

How to pass bean method as parameter?

+4
source share
4 answers

I don't know what your goal is for GenericType. In any case, try the code below.

 ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); Unidade u = new Unidade(); u.setUnidSigla("KG"); WebResource webResource = client.resource("http://localhost:8080/RestauranteWeb/rest/unidades/7"); Unidade response = webResource.accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .post(Unidade.class, u); 
+1
source

Using Jackson as a Serializer / DeSerializer

If your Unidade object is annotated with a Jackson and / or Deserializer , you should be able to POST with a BODY that contains JSON representing the Unidade object. It should be magically deserialized and rebuilt as an object on the server side.

Attention!

Make sure you add the Content-Type header in the POST request with the value application/json . Without this headline, your Jersey may not know what to do with the body.

You would use Jackson ObjectMapper to serialize your Unidade object to JSON and send it instead of all that GenericType .

I have an implementation of both Jersey and RESTEasy that work so easily with Jackson.

+3
source

How to pass bean method as parameter?

Checkout the post method:

  /** * Invoke the POST method with a request entity that returns a response. * * @param <T> the type of the response. * @param c the type of the returned response. * @param requestEntity the request entity. * @return an instance of type <code>c</code>. * @throws UniformInterfaceException if the status of the HTTP response is * greater than or equal to 300 and <code>c</code> is not the type * {@link ClientResponse}. * @throws ClientHandlerException if the client handler fails to process * the request or response. */ <T> T post(Class<T> c, Object requestEntity) throws UniformInterfaceException, ClientHandlerException; 

The method takes two parameters. The first parameter is the expected response type, and the second is the object that will be placed in the request body.

What happens here, when executing the request, Jersey will serialize the object passed as the request object into the JSON string (therefore, you set the accept(MediaType.APPLICATION_JSON) header accept(MediaType.APPLICATION_JSON) ). When a response is received from the server, Jersey deserializes it (inverted process, as in the case of requestEntity ), and returns an object to you.

But what if my method receives more than one parameter? Because the message method only perceives 1

Well, you cannot do it with JAX-RS, and actually it makes little sense. You can pass multiple parameters to a method like @PathParam or @MatrixParam , but there can only be one associated with the body (well, you only have one body in our request, right?). The answer to the question on this question and verification of the use of @PathParam or @MatrixParam

Suppose, instead of returning a "Unidade" class, my method returns a string. That way it will get β€œUnidade” as a parameter and return β€œString”. How can I get it in this case by passing the "Unidade" instance as before?

I think you could achieve this with post(String.class, unidadeInstance) . The first parameter does not have to match the second. It is valid for accepting one parameter and returning another. It’s even permissible to accept a parameter and not return anything in the body (for example, you did this in the code attached to your question). You can accept the body and send a response containing 201 Created status and a Location header pointing to the URL of the newly created resource.

+2
source

I'm not sure if this helps, but I had a similar problem. In my scenario, I need a web service that was supposed to get a bunch of values ​​that were organized as a kind of profile. But this service has to cope with the fact that there are more profiles where still old customers use this service. The interface should be as static as possible.

Our solution is very simple. We publish only one text field as the content of the message. But this includes the serialized state of the profile object in JSON. Pseudocode:

 public class Profile1 { ... public String asJSON() { JSONObject obj = new JSONObject(); obj.put("profileAtr1", profileAtr1); ... return obj.toString() } } formParams.put("profile", profile.asJSON()); client.post(formParams); 

Thus, it does not automatically deserialize, but it is easy to do it manually. We do this with a generic Profile object that can be created from a JSON String in the constructor. Pseudocode:

 public GenericProfile { public GenericProfile(String json) { JSONObject obj = new JSONObject(json); String profileName = obj.getString("profileName"); if (profileName.equals("Profile1") { this = new Profile1(obj); // I know this is not working ;) My impl. is a litle bit more complecated as that. I think i use a static method in the generic profile to create an instance i need. } ... } } 

And then in your web service there is only one form parameter for processing and deserialization;) Pseudocode:

 public ResponseEnvelope coolServiceFunction(@FormParam("profile") String profileData) { GenericProfile profile = new GenericProfile(profileData); if (profile instanceof Profile1) { do what you want } } 

Sorry for the pseudo-code, but I have alleady shutdown my dev vm and no longer have access to any repository :( I think the biggest advantages of this solution are: 1. It can transport everything that you can package in JSON. Thus, I I transmit BASE64 encoded binary blocks and highly encrypted text data 2. The simplest example of a POST REST Framework tutorial will provide everything you need to do 3. You can be sure that your interface will remain for a long period of time.

Hope that helps

0
source

Source: https://habr.com/ru/post/1492594/


All Articles