0

This is my custom class:

@XmlRootElement
class Request{
    private String name;
    private String age;

    public Request(){

    }

    public Request(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return this.name;
    }

}

This is my service:

@PATH("/webapp/")
class RestService{

    @POST
    @Produces(MediaType.APPLICATION_XML)
    @PATH("getNameFromRequest")
    public String getNameFromRequest(@FormPara Request request) {
        System.out.println(request.getName())  //Here request.getName() is null !!!
        return request.getName();
    }
}

This is how I programmatically make the restful call using a client service created by JAXRSClientFactory

RestService service = JAXRSClientFactory.create("http://test:8080", RestService.class);

service.getNameFromRequest(new Request("Rachel","23"))

However, it seems that "Rachel" is not passed into the request at all.

If I use Web-browser to request against this, the name will be set:

http://test:8080/webapp?name=Rachel

Could someone please help me why I cannot programmatically make the restful call?

Guifan Li
  • 1,543
  • 5
  • 14
  • 28
  • You need to use JAX-RS client API to call your web service from a Java client – Trash Can Jul 25 '17 at 03:51
  • @Dummy Emm, is this part: RestService service = JAXRSClientFactory.create("http://test:8080", RestService.class) service.getNameFromRequest(new Request("Rachel","23")); the JAX-RS client API call the web service ? – Guifan Li Jul 25 '17 at 03:58
  • https://docs.oracle.com/javaee/7/api/javax/ws/rs/client/package-summary.html this is the APIs I was referring to – Trash Can Jul 25 '17 at 16:39

1 Answers1

0

your service should have @Consumes annotation on your service

like this

@PATH("/webapp/")
class RestService{
@POST
@Consumens(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
@PATH("getNameFromRequest")
public String getNameFromRequest(JAXBElement<Request> request) {
    System.out.println(request.getName()) ; 
    return request.getName();
}

}

And path to this service will be http://<hostname or ip adderss:8080 if default configuration >/<your app root folder name or root path>/webapp/getNameFromRequest

and client code will be like

Request request = new Request("Rachel","23");


webTarget.path("webapp/getNameFormRequest").post(new JAXBElement<Request>(new QName("Request"), Request.class, request));

then it will work

harsha kumar Reddy
  • 1,251
  • 1
  • 20
  • 32