Reputation: 1517
I want to make a POST request to REST webservice and I want to pass customer java object with the POST request. But response shows 415 error code Unsupported Media type.
My REST Client
Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/cthix/rest/v1/m2");
Customer cust = new Customer();
cust.setId(101L);
ObjectMapper mapper = new ObjectMapper();
String jsonCustomer = mapper.writeValueAsString(cust);
ClientResponse restResponse = resource.accept("application/json").
post(ClientResponse.class,jsonCustomer);
System.out.println(restResponse.getStatus());
if(restResponse.getStatus()==200){
String output = restResponse.getEntity(String.class);
PrintWriter pw = response.getWriter();
pw.print(output);
pw.flush();
pw.close();
}
My REST SERVICE:
@Path(value = "/v1")
public class V1_status {
@Path("/m2")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Customer returnCustomerDetails(Customer customer){
Set<Integer> phones = new HashSet<Integer>();
phones.add(123424541);
phones.add(123432123);
List hobbies= new ArrayList();
hobbies.add("Swimming");
hobbies.add("coding");;
customer.setHobbies(hobbies);
customer.setPhones(phones);
customer.setCity("Noida");
customer.setName("abhishek");
return customer;
}
}
Please guide how to fix it.
Upvotes: 1
Views: 10101
Reputation: 1517
I actually got problem, the thing which I missed was: resource.type("application/json")
ClientResponse restResponse = resource.accept("application/json").type("application/json").post(ClientResponse.class,cust);
Two points which need to be paid attention:
1) No need to convert Customer object to Json manually.(if u convert also no issue at all)
2) No need to use @Consumes(MediaType.APPLICATION_JSON). if u even use it, no problem. This only tells, this method will accept this MediaType. If u dont use @Consumes annotation, REST Service method will try to consume it whatever format it is coming, and will try to parse the data coming from client to its appropriate Model object (in argument). If successfully parsed no problem. If data is not in appropriate format to sync with Model object. It will throw exception. That's it.
Upvotes: 2
Reputation: 1658
The problem is that you are telling the service to consume JSON, the parameter customer is of type Customer, and in your REST client you are sending a string.
You need to
Upvotes: 1