如何在Apache Camel / CXF REST Web服务中访问POST / PUT请求的JSON请求主体

时间:2012-10-17 10:06:00

标签: java json rest cxf apache-camel

我正在尝试将JSON请求主体传递给我在Apache Camel应用程序中使用CXFRS制作的REST Web服务。

我想访问处理器中传递的JSON请求。

REST网址:

http://localhost:8181/mywebservice/Hello/name/{request_param}

虽然我在请求正文中发布了JSON,但仍然在我的处理器exchange.getIn().getBody()中始终返回{request_param}而不是请求JSON。

我的REST网络服务如下:

@Path("/name/")
@Consumes({"application/json" ,"application/xml"})
public class HelloRest {
    @POST
    @Path("/{name}")
    public TestPojo sayHi(@PathParam("name") String name) {
        return new TestPojo(name);
    }
}

1 个答案:

答案 0 :(得分:0)

服务器部分:

    @POST
@Path("/")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String add(MappingUser newUser){
    UserEntity userEntity = new UserEntity(newUser.getNickname(), newUser.getPassword());
    boolean ret = myDB.addUser(userEntity);

    //sends the return value (primitive type) as plain text over network
    return String.valueOf(ret);
}

客户端部分:

 public boolean addUser(User user){
    WebResource resource = client.resource(url).path("/");

    String response = resource
            //type of response
            .accept(MediaType.TEXT_PLAIN_TYPE)
            //type of request
            .type(MediaType.APPLICATION_JSON_TYPE)
            //method
            .post(String.class, user);

    return Boolean.valueOf(response);
}