簡體   English   中英

如何使用curl使用2個參數進行POST? 休息。 Java的

[英]How to POST with 2 parameters using curl? REST. Java

我想在方法“ createPost”中引入兩個String參數(類型和內容)。

我正在使用此行:

curl -i -u pepe:pepe -d 'type=Link&content=www' --header "Content-Type: application/json"  http://localhost:8080/web-0.0.1-SNAPSHOT/api/user/post

但是...該行在第一個參數中引入“ type = Link&content = www”,而第二個參數留空。

方法是這樣的:

@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createPost(@FormParam("type") String type,  @FormParam("content") String content) { 
    postEJB.createPostUserRest(type, content);
    URI userURI = uriInfo.getAbsolutePathBuilder().build();
    return Response.created(userURI).build();
}

如何在第一個輸入“ Link”,在第二個輸入“ www”?

非常感謝所有人,對不起我的英語不好。

這里有幾個問題:

  • 要確保curl發送POST請求,請使用-X POST
  • 方法createPost需要MediaType.APPLICATION_JSON ,它與curl-d選項不兼容。 (此外,如果我沒記錯的話,讓這種媒體類型正常工作是很棘手的,盡管肯定是可能的。) 我建議改為使用MediaType.APPLICATION_FORM_URLENCODED ,它與curl -d兼容,並且更容易使工作正常。
  • 要傳遞多個表單參數,可以使用多個-d選項

總結一下,將Java代碼更改為:

@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createPost(@FormParam("type") String type,  @FormParam("content") String content) { 
    postEJB.createPostUserRest(type, content);
    URI userURI = uriInfo.getAbsolutePathBuilder().build();
    return Response.created(userURI).build();
}

和curl要求:

curl -X POST -d type=Link -d content=www -i -u pepe:pepe http://localhost:8080/web-0.0.1-SNAPSHOT/api/user/post

請注意,我刪除了Content-Type: application/json標頭。 默認值為application/x-www-form-urlencoded ,也由-d工作方式隱含,並且由我們更改上述Java代碼的方式所必需。

暫無
暫無

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

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