解析请求参数而无需编写包装器类 [英] Parse request parameters without writing wrapper class

查看:57
本文介绍了解析请求参数而无需编写包装器类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to handle json requests and parse the request parameters in dropWizard?

@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\"}";
}

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

I wrote the above code and tried the following request.

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

但是request.getParameterMap(){}

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

How to parse the parameters without writing a wrapper class?

推荐答案

您的curl命令可能需要在数据周围加上一些引号(如果没有它们,我会得到一个错误):

Your curl command may need some additional quotes around the data (I'm getting an error without them):

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

您正在发送POST请求,没有 URL参数.我不确定为什么您期望在那里看到一些东西.

You are sending a POST request without URL parameters. I'm not sure why you are expecting to see something there.

我不知道您使用的是哪个版本的dropwizard,但是当对方法进行注释时,我无法使@POST@Path("/something")注释的组合起作用.我正在获取HTTP ERROR 404.

I don't know which version of dropwizard you are using but I couldn't make the combination of @POST and @Path("/something") annotation to behave when a method is annotated. I'm getting HTTP ERROR 404.

要使其正常工作,我必须将@Path注释移至资源/类级别,并在方法中仅保留@Post注释.

To make it work I have to move the @Path annotation to the resource/class level and leave only the @Post annotation at the method.

@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的形式获取请求的正文,请执行上述操作.从此处获取:如何使用Jersey获得完整的REST请求正文?

To get the body of the request as String just do as above. Taken from here: 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"}
>>>>>>>>>

这篇关于解析请求参数而无需编写包装器类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆