我想向REST Web服务发出POST请求,并且希望通过POST请求传递客户Java对象。但是响应显示415错误代码不支持的媒体类型。
我的REST客户端
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();
}
我的REST服务:
@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;
}
}
请指导如何修复它。
我实际上遇到了问题,我想念的是:resource.type(“ application / json”)
ClientResponse restResponse = resource.accept("application/json").type("application/json").post(ClientResponse.class,cust);
需要注意两点:
1)无需手动将Customer对象转换为Json。(如果您也完全转换也没有问题)
2)无需使用@Consumes(MediaType.APPLICATION_JSON)。如果您甚至使用它,也没问题。这仅说明,此方法将接受此MediaType。如果您不使用@Consumes批注,则REST Service方法将尝试使用它即将使用的任何格式,并将尝试将来自客户端的数据解析到其适当的Model对象(在参数中)。如果解析成功就没问题。如果数据格式不正确,则无法与Model对象同步。它将引发异常。而已。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句