[英]How to read JSON request body using Dropwizard
我一直在編寫簡單的dropwizard應用程序,一切正常,直到我不得不更改請求類型。 因為我之前從Header得到了我的參數,現在我必須從JSON請求的主體中獲取它們。 最可悲的是 - 沒有關於dropwizard或任何文章的完整文檔,這對我有幫助。 這是我的代碼:
@Path("/actors")
@Produces("application/json")
public class ActorResource {
private final ActorDAO dao;
public ActorResource(ActorDAO dao) {
this.dao = dao;
}
@POST
@UnitOfWork
public Saying postActor(@HeaderParam("actorName") String name,@HeaderParam("actorBirthDate") String birthDate) {
Actor actor = dao.create(new Actor(name,birthDate));
return new Saying("Added : " + actor.toString());
}
有沒有人有辦法解決嗎?
根據要求,這是一個片段,展示你想要做什么:
@Path("/testPost")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {
@POST
public Response logEvent(TestClass c) {
System.out.println(c.p1);
return Response.noContent().build();
}
public static class TestClass {
@JsonProperty("p1")
public String p1;
}
}
TestClass是我的身體。 澤西知道,它需要將身體解析為該物體。
然后,我可以卷起我的API:
curl -v -XPOST "localhost:8085/api/testPost" -H "Content-Type: application/json" -d '{"p1":"world"}'
Jersey知道通過方法參數做什么,並通過Jackson Annotation如何對待JSON。
希望有所幫助,
阿圖爾
編輯:對於更手動的方法,您可以:
在你的post方法中,注入
@Context HttpServletRequest request
從注入的請求中,將主體寫入String以進行處理:
StringWriter writer = new StringWriter();
try {
IOUtils.copy(request.getInputStream(), writer);
} catch (IOException e) {
throw new IllegalStateException("Failed to read input stream");
}
現在使用任何庫將該字符串映射到您想要的任何對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.