我使用Angular 4 HttpClient编写了此代码,应该与一个简单的RESTful JAVA Web服务进行通信并获得一个JSON字符串:

this.client.post('http://localhost:8080/ToDoService/rest/service/create', {id: 'foo', todo: 'bar'}).subscribe((data) => {
    console.log("Got data: ", data);
}, (error) => {
    console.log("Error", error);
})


没用我的意思是idtodo参数没有传递到REST后端。

另一方面,如果我将以上代码更改为:

this.client.post('http://localhost:8080/ToDoService/rest/service/create?id=foo&todo=bar', '').subscribe((data) => {
    console.log("Got data: ", data);
}, (error) => {
    console.log("Error", error);
})


一切正常,但是我确定第二个片段是错误的。看起来很不对劲。

你能给我个提示并指出我的错误吗?

压力

JAVA后端:

@Path("/service")
public class Rest extends Application{
    @POST
    @Path("/create")
        public Response printMessage(@QueryParam("id") String userId, @QueryParam("todo") String toDo) {
            JSONObject result = new JSONObject();

            result.put("id", userId);
            result.put("todo", toDo);

            return Response.status(200).entity(result.toString()).build();
        }
}

最佳答案

您正在映射QueryParams,需要将该有效负载映射到Map或Object:

class PayLoad {
    private String id;
    private String todo;
    // Getter and Setters
}

@Path("/service")
public class Rest extends Application{
    @POST
    @Path("/create")
        public Response printMessage(@RequestBody PayLoad payload) {
            JSONObject result = new JSONObject();

            result.put("id", payload.getId());
            result.put("todo", payload.getTodo());

            return Response.status(200).entity(result.toString()).build();
        }
}


希望这可以帮助!

10-04 22:21
查看更多