[英]Java: Get JSON from POST with HttpServletRequest?
我正在嘗試使用HttpServletRequest或UriInfo來獲取POST請求的主體。 鑒於此類課程(針對此問題減少):
@Path("/nodes")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_JSON })
public class Nodes {
public NodeResource() {
//initial stuff goes here
}
/**
* gives an empty response. For testing only!
*/
@POST
@Consumes("application/json")
@Path("{id}/test-db-requests")
public Response giveNodes(@PathParam("id") final String id, @Context HttpServletRequest request, @Context UriInfo uriInfo){
//String readReq = request.getQueryString(); //would work for GET
MultivaluedMap<String,String> readParams = uriInfo.getQueryParameters();
LOG.debug("what is readParams?", readParams); //goes, but shows nothing
if (readParams != null) {
LOG.debug("null or not?"); //goes, too
for (Map.Entry<String,List<String>> entry: readParams.entrySet()) {
List<String> values = entry.getValue();
LOG.debug("params POST key: {}", entry.getKey()); // goes not
for (String val: values) {
LOG.debug("params POST values: {}", val);
}
LOG.debug("params POST next entry:::");
}
}
List<?> results = null; //currentDBRequest(id);
List<?> content = new ArrayList<>();
if (results != null) {
content = results;
}
return Response.ok(content).build();
}
}
而不是使用
MultivaluedMap<String,String> readParams = uriInfo.getQueryParameters();
//not possible at all - for GET only!? See first comment.
我也試過用
Map<String,String[]> readParams = request.getParameterMap();
//what is about this one?
當然有不同的代碼。 但這也行不通。
所以,當我用以下正文發出像/nodes/546c9abc975a54c398167306/test-db-requests
這樣的簡單請求時
{
"hi":"hello",
"green":"tree"
}
(使用JSON數組不會改變任何東西)
和HEADER中的東西(一些信息):
Content-Type: application/json; charset=UTF-8
Accept: application/json, text/plain, */*
Connection: keep-alive
結果令人失望, readParams
不為null
,但不包含任何數據。 在我開始使用getReader
之前,我想問:我做錯了什么? 在我的POST,我的Java代碼或使用的HttpServletRequest
方法中是否存在問題? 謝謝!
相關問題(我找到了一些可能的解決方案),其中包括:
好吧,傑克遜實際上會為我做這件事。 只需使用您要使用的方法的參數。 (見下面的例子。)
但是你可能不會將POST與id參數結合使用。 POST通常用於保存新資源,這些資源沒有id(在DB中,是主鍵)。 此外,路徑/api/{resource_name}/{id}/{some_view}
對GET很有用。 對於GET(單個條目)或PUT(更新現有條目),只需api/{resource_name}/{id}
。
假設您在Pet.class的資源中。 您希望捕獲此類的POST,以便根據視圖test-db-requests
對它們執行特殊操作。 然后做:
@POST
@Consumes("application/json")
@Path("{id}/test-db-requests")
public Response giveNodes(final String pet, @PathParam("id") final String id){
//do stuff for POST with a strigified JSON here
}
要么
@POST
@Path("{id}/test-db-requests")
public Response giveNodes(final Pet pet, @PathParam("id") final String id){
//do stuff for POST with an instance of pet here (useful for non
//polymorphic resources
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.