【问题标题】:Parse request parameters without writing wrapper class解析请求参数而不编写包装类
【发布时间】:2016-11-24 11:14:33
【问题描述】:

dropWizard中如何处理json请求并解析请求参数?

@POST
@Path("/test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String test(@Context final HttpServletRequest request) {
    JSONObject data=new JSONObject();
    System.out.println(request);
    System.out.println(request.getParameterMap());
    System.out.println(">>>>>>>>>");

    return "{\"status\":\"ok\"}";
}

我编写了上面的代码并尝试了以下请求。

curl -XPOST  -H "Content-Type: application/json" --data {"field1":"val1", "field2":"val2"} http://localhost:8080/test 

但是request.getParameterMap(){}

如何在不编写包装类的情况下解析参数?

【问题讨论】:

    标签: jersey dropwizard pojo


    【解决方案1】:

    您的curl 命令可能需要一些额外的数据引号(没有它们我会收到错误消息):

    curl -H "Content-type: application/json" -X POST -d '{"field1":"tal1", "field2":"val2"}' http://localhost:8080/test
    

    您正在发送一个POST 请求没有 URL 参数。我不知道你为什么期待在那里看到一些东西。

    我不知道您使用的是哪个版本的dropwizard,但我无法使@POST@Path("/something") 注释的组合在注释方法时起作用。我收到了HTTP ERROR 404

    为了使其工作,我必须将@Path 注释移动到资源/类级别,并在方法中只保留@Post 注释。

    @Path("/test")
    public class SimpleResource {
    
        @POST
        @Consumes(MediaType.APPLICATION_JSON)
        public String test(final String data) throws IOException {
            System.out.println("And now the request body:");
            System.out.println(data);
            System.out.println(">>>>>>>>>");
    
            return "{\"status\":\"ok\"}";
        }
    }
    

    要以String 的形式获取请求的正文,只需执行上述操作即可。取自这里:How to get full REST request body using Jersey?

    控制台看起来像:

    INFO  [2016-11-24 15:26:29,290] org.eclipse.jetty.server.Server: Started @3539ms
    And now the request body:
    {"field1":"tal1", "field2":"val2"}
    >>>>>>>>>
    

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多