簡體   English   中英

返回新生成的id restful service post

[英]return newly generated id restful service post

我正在嘗試在我的REST Web服務中編輯我的create方法,因此它應該從對象返回新創建的ID。 過去兩天我一直在努力,但我必須做一些非常錯誤的事情......

這是服務器端編輯的create方法:

@POST
@Consumes({"application/xml", "application/json"})
@Path("withID")
@Produces("text/plain")
public String create2(Users entity) {
    getEntityManager().persist(entity);
    getEntityManager().flush();
    System.out.println("new id: " + entity.getId());
    return String.valueOf(entity.getId());
}

它基於(通過netbeans)生成的count()方法,如下所示:

@GET
@Path("count")
@Produces("text/plain")
public String countREST() {
    return String.valueOf(super.count());
}

如果我從我的客戶端請求添加新的Users對象,它的工作方式與預期的一樣。 新用戶正在添加到數據庫中。 在GlassFish服務器日志中,我看到System.out.println命令顯示的新創建的ID。 但是,如果我通過netbeans中的TestRestful Web服務進行測試,將客戶端生成的XML代碼粘貼到正確的窗口並點擊TEST按鈕,我會收到HTTP狀態415 - 不支持的媒體類型錯誤。

我做了一些研究,發現了這個問題。 所以我的猜測而不是返回一個String,我應該返回一個具有201 CREATED狀態的Response對象並調整標題或其他東西? 我檢查了春天的例子,但由於我沒有使用spring,我不知道如何調整create2方法代碼...但是我試了但是我錯過了一些部分:

@POST
@Consumes({"application/xml", "application/json"})
@Path("withID")
@Produces("text/plain") //should this change to application/xml?
public Response create2(Users entity) {
    getEntityManager().persist(entity);
    getEntityManager().flush();
    System.out.println("new id: " + entity.getId());

    //Response response = Response.created(... + "withID/" + entity.getId()); //response need an URI, can I get this through the entity object?

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

我希望我走在正確的軌道上。 對不起,很長的帖子,希望有人可以幫助我。 提前致謝!

編輯:現在的工作示例:

@POST
@Consumes({"application/xml"})
@Path("withID")
@Produces({"application/xml"})
public Response create2(Users entity) {
    getEntityManager().persist(entity);
    getEntityManager().flush();
    return Response.status(201).entity(entity.getId().toString()).build();
}

我不知道NetBeans的東西,我們正在使用Spring ..但返回一個Response對象是一個好主意,我們總是這樣做,我們也返回一個創建的ID:

return Response.status(200).entity(createdObject.getId().toString()).build();

不支持的MediaType非常煩人。當你提到客戶端生成的xml數據時,不確定你在說什么。我們正在使用JSON,即使響應只是一個簡單的字符串,我們告訴create方法生成json:

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Transactional
public Response create(T source) {
}

我們在命令行上使用的簡單測試:

$ curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"id":95, "additional":"stuff..."}' "http://localhost:8080/rest/resource"

好吧,祝你好運。 看起來你走在正確的軌道上。

而不是返回一些自定義blob,只需使用協議。

因此,請考慮將響應中的位置標頭與uri一起用於新資源。 你正在做一個休息服務,所以你的ID當然是URI(對吧?)。

Jim Webber寫了一本關於設計REST實踐的REST Web服務的好書,它詳細解釋了如何基於這樣的簡單原則設計REST api。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM