简体   繁体   中英

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 @QueryParam s 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 @FormParam s 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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM