Restlet implementing post with json receive and response

后端 未结 2 1005
我在风中等你
我在风中等你 2021-02-06 11:09

First, what i wanted to know is what i am doing is the right way to do it.

I have a scenario where i have will receive a json request and i have to update the database w

相关标签:
2条回答
  • 2021-02-06 11:23

    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);
        }
    }
    
    0 讨论(0)
  • 2021-02-06 11:25

    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.

    0 讨论(0)
提交回复
热议问题