简体   繁体   中英

REST passing Parameters with Java

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

IE

@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

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

}

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

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");

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