postgresql Restlet 使用 json 接收和响应实现 post

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1352202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 23:49:53  来源:igfitidea点击:

Restlet implementing post with json receive and response

jsonpostgresqlrestrestlet

提问by

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 with that, once the db is updated i have to respond back with the json acknowledgment.

我有一个场景,我将收到一个 json 请求,我必须用它更新数据库,一旦数据库更新,我必须用 json 确认响应。

What i have done so far is create the class extending application as follows:

到目前为止,我所做的是创建类扩展应用程序,如下所示:

     @Override  
     public Restlet createRoot() {  
         // Create a router Restlet that routes each call to a  
         // new instance of ScanRequestResource.  
         Router router = new Router(getContext());  

         // Defines only one route  
         router.attach("/request", RequestResource.class);  

         return router;  
     }  

My resource class is extending the ServerResource and i have the following method in my resource class

我的资源类正在扩展 ServerResource 并且我的资源类中有以下方法

@Post("json")
public Representation post() throws ResourceException {
    try {
        Representation entity = getRequestEntity();
        JsonRepresentation represent = new JsonRepresentation(entity);
        JSONObject jsonobject = represent.toJsonObject();
        JSONObject json  = jsonobject.getJSONObject("request");

        getResponse().setStatus(Status.SUCCESS_ACCEPTED);
        StringBuffer sb = new StringBuffer();
        ScanRequestAck ack = new ScanRequestAck();
        ack.statusURL = "http://localhost:8080/status/2713";
        Representation rep = new JsonRepresentation(ack.asJSON());

        return rep;

    } catch (Exception e) {
        getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    }

My first concern is the object i receive in the entity is inputrepresentation so when i fetch the jsonobject from the jsonrepresentation created i always get empty/null object.

我首先关心的是我在实体中收到的对象是 inputrepresentation,所以当我从创建的 jsonrepresentation 中获取 jsonobject 时,我总是得到空/空对象。

I have tried passing the json request with the following code as well as the client attached

我尝试使用以下代码以及附加的客户端传递 json 请求

function submitjson(){
alert("Alert 1");
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/thoughtclicksWeb/request", 
        contentType: "application/json; charset=utf-8",
        data: "{request{id:1, request-url:http://thoughtclicks.com/status}}",
        dataType: "json",
        success: function(msg){
            //alert("testing alert");
            alert(msg);
        }
  });
};

Client used to call

客户端用来调用

    ClientResource requestResource = new ClientResource("http://localhost:8080/thoughtclicksWeb/request");
        Representation rep = new JsonRepresentation(new JSONObject(jsonstring));
    rep.setMediaType(MediaType.APPLICATION_JSON);
    Representation reply = requestResource.post(rep);

Any help or clues on this is hight appreciated ?

对此有何帮助或线索表示高度赞赏?

Thanks, Rahul

谢谢,拉胡尔

回答by Ashwin Jayaprakash

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:

仅使用 1 个 JAR jse-xyz/lib/org.restlet.jar,您可以在客户端手动构建 JSON 以处理简单请求:

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.jarand jse-x.y.z/lib/org.restlet.jar:

在服务器端,只使用 2 个 JAR - gson-xyzjarjse-xyz/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);
    }
}

回答by laz

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

当我使用以下 JSON 作为请求时,它可以工作:

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

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

请注意示例中没有的双引号和额外的冒号。