11

I've built a REST webservice with some webmethods. But I don't get it to work passing parameters to these methods.

I.E.

@GET
@Path("hello")
@Produces(MediaType.TEXT_PLAIN)
public String hello(String firstName, String lastName){

    return "Hello " + firstname + " " + lastname
}

How would I invoke that method and how to pass the parameters firstname and lastname? I tried something like this:

ClientConfig config = new DefaultClientConfig();

Client client = Client.create(config);

WebResource service = client.resource(getBaseURI());

ClientResponse response = service.path("hello")
.accept(MediaType.TEXT_PLAIN).put(ClientResponse.class);

But where do I add the parameters?

Thank you for your help, best regards, Chris

Chris
  • 566
  • 1
  • 8
  • 20

3 Answers3

10

If you are using SpringMVC for REST api development you can use

@RequestParam("PARAMETER_NAME");

In case of jersey you can use

@QueryParam("PARAMETER_NAME");

Method look like this

public String hello(@RequestParam("firstName")String firstName, @RequestParam("lastName")String lastName){

return "Hello " + firstname + " " + lastname

}

kundan bora
  • 3,821
  • 2
  • 20
  • 29
7

This tutorial should be of help. To include parameters you will need to use the @PathParam command as shown in this previous SO Post.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
  • thank you helped me alot. But what if my method wants an array of Strings? – Chris Mar 28 '12 at 11:54
  • @Chris: This should help: http://stackoverflow.com/questions/5484209/pass-array-as-a-parameter-in-restful-webservice – npinti Mar 28 '12 at 11:56
  • Thank you very much. That link was also helpful to the context of your last link: http://stackoverflow.com/questions/5718575/how-can-i-grab-all-query-parameters-in-jersey-jaxrs – Chris Mar 28 '12 at 12:11
  • There i have explain more method for this https://stackoverflow.com/a/70656772/7390856 – Anuj Dhiman Jan 10 '22 at 17:49
2

This will help you

ClientResponse response = resource.queryParams(formData).post(ClientResponse.class, formData);

where formData is

MultivaluedMap formData = new MultivaluedMapImpl();


formData.add("Key","Value");
formData.add("Key","Value");
...
...
...
formData.add("Key","Value");
Yogesh Prajapati
  • 4,770
  • 2
  • 36
  • 77