Sriram Sridharan
Sriram Sridharan

Reputation: 740

Spring MVC RestFul service + Jersey Client 400 Bad Request

I have created a RESTful webservice in Spring, and am trying to call it via a Jersey client. Here's my Controller method

@RequestMapping(value = "/create",
                method = RequestMethod.POST,consumes={MediaType.APPLICATION_JSON_VALUE},
                produces={MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<User> createUser(@RequestBody User user ){
    User u = null;
    HttpStatus statusCode;
    try{
        userService.create(user);
        u = userService.getUserById(user.getId());
        statusCode = HttpStatus.CREATED;
    }catch(Exception e){
        logger.error("Could not create user ", e);
        u = null;
        statusCode = HttpStatus.CONFLICT;
    }

    return new ResponseEntity<User>(u, statusCode);
}

When I call this web service from a Jersey client, I get 400 Bad Request error. Here's the client that calls this service

HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("xxxx", "yyyy");

final Client client = ClientBuilder.newClient();
client.register(feature);

WebTarget webTarget = client.target("http://localhost:8080/MyWeb/api").path("user/create");

Form form = new Form();
form.param("id", "jersey");
form.param("firstName", "Jersey");
form.param("lastName", "Client");


/*User user = webTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), User.class);*/
Invocation.Builder invocationBuilder =  webTarget.request(MediaType.APPLICATION_JSON_TYPE);
Response response = invocationBuilder.post(Entity.entity(form, MediaType.APPLICATION_JSON_TYPE));

System.out.println(response.getStatus());
System.out.println(response.getStatusInfo());

I tried playing around with the MediaType values in both the service as well as the client, but nothing works.

I've to tell you that I'm totally new to this and this is like my first stint at RESTful web services.

Please help me understand what mistake I'm doing..

Upvotes: 0

Views: 723

Answers (1)

CarlosJavier
CarlosJavier

Reputation: 1045

I think you are telling to the service you are sending JSON in the payload, but you are sending form params instead, when you do:

form.param("id", "jersey");

and the following lines, you are emulating a POST just like creating an HTML Form with submission button.

You may have to declare a class User in your client, instance one object of this class and fill the properties as:

User user = new User();
user.setId("jersey");

and then send this object in the POST (i haven't work with Invocation.Builder but it sure have some post method with an object as parameter), Jersey client should take care of the serialization sending the JSON string in the payload.

Upvotes: 1

Related Questions