Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass an @FormParam to a RESTful service from another method?

DISCLAIMER: I did search exhaustively for an answer to this question, and yes, I did find this other question: https://stackoverflow.com/questions/10315728/how-to-send-parameters-as-formparam-to-webservice . But firstly, that question is asking about Javascript, while I am asking about Java, and secondly, it has no answers anyway. So on to the question...

With RESTful services, passing @QueryParams into an @GET service is fairly easy, as you can simply append variables name/value pairs to a URL and use it to hit the server from within the program. Is there a way to do this with @FormParams as well?

For example, let's say I have the following RESTful service:

@POST
@Produces("application/xml")
@Path("/processInfo")
public String processInfo(@FormParam("userId") String userId,
                          @FormParam("deviceId") String deviceId,
                          @FormParam("comments") String comments) {
    /*
     * Process stuff and return
     */
}

... and let's say I also have another method somewhere else in my program like this:

public void updateValues(String comments) {

    String userId = getUserId();
    String deviceId = getDeviceId();

    /*
     * Send the information to the /processInfo service
     */

}

How can I perform the commented out action in the second method?

NOTE: Assume these methods are not in the same class or package. Also assume that the RESTful service is hosted on a different server than the machine you are running your method from. As such, you must access the method and pass the values in in a RESTful way.

Thank you for your help!

like image 451
asteri Avatar asked Sep 07 '12 09:09

asteri


1 Answers

Using @FormParam you can bind form parameters to a variable.You can find a sample here.

Secondly ,In order to call rest service internally form your java method code you will have to use jersey client.Example code can be found here.

You can pass form parameters using jersey client form as follows.

Create form

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(UriBuilder.fromUri("http://localhost:8080/api").build());

Form f = new Form();    
f.add("userId", "foo");    
f.add("deviceId", "bar");    
f.add("comments", "Device");  

pass it to Restful method.

service.path("processInfo").accept(MediaType.APPLICATION_XML).post(String.class,f);

reference

like image 58
Prabash B Avatar answered Sep 18 '22 19:09

Prabash B