Restlet implementing post with json receive and response

那年仲夏 提交于 2019-12-03 03:41:51

Using just 1 JAR jse-x.y.z/lib/org.restlet.jar, you could construct JSON by hand at the client side for simple requests:

ClientResource res = new ClientResource("http://localhost:9191/something/other");

StringRepresentation s = new StringRepresentation("" +
    "{\n" +
    "\t\"name\" : \"bank1\"\n" +
    "}");

res.post(s).write(System.out);

At the server side, using just 2 JARs - gson-x.y.z.jar and jse-x.y.z/lib/org.restlet.jar:

public class BankResource extends ServerResource {
    @Get("json")
    public String listBanks() {
        JsonArray banksArray = new JsonArray();
        for (String s : names) {
            banksArray.add(new JsonPrimitive(s));
        }

        JsonObject j = new JsonObject();
        j.add("banks", banksArray);

        return j.toString();
    }

    @Post
    public Representation createBank(Representation r) throws IOException {
        String s = r.getText();
        JsonObject j = new JsonParser().parse(s).getAsJsonObject();
        JsonElement name = j.get("name");
        .. (more) .. .. 

        //Send list on creation.
        return new StringRepresentation(listBanks(), MediaType.TEXT_PLAIN);
    }
}

When I use the following JSON as the request, it works:

{"request": {"id": "1", "request-url": "http://thoughtclicks.com/status"}}

Notice the double quotes and additional colon that aren't in your sample.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!