我想向 REST 网络服务发出 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 服务方法将尝试使用它的任何格式,并将尝试将来自客户端的数据解析为其适当的模型对象(在参数中)。如果解析成功没问题。如果数据的格式不适合与模型对象同步。它会抛出异常。就是这样。
关于java - 返回 415 Unsupported Media Type REST 客户端的响应状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32409793/