从 JAX-RS 中的 POST 请求接收参数

Receive parameters from POST requests in JAX-RS

我有一个方法可以在 POST 请求中接受 JSON。从 POST 请求中获取参数的唯一方法是使用 @FormParam

但是我使用 Android 使用 web 服务并且我那里没有 HTML 表单。

@Path("/app")
public class WebApi {

    @POST
    @Path("/prog")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Res method(@FormParam("name") Res name){

        try{
            System.out.println("Id:" +name.getId());
            System.out.println("Name: "+name.getName());
            return name;
        }catch(Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }
}

Res 是一个实体 class:

@XmlRootElement
public class Res {

    @XmlElement int id;
    @XmlElement String name;

    // Default constructor, getters and setters ommited
}

请告诉我从POST请求中接收参数的方式。

如果参数作为 json 包含在请求实体主体中,则不需要应用 @FormParam 注释,通常 jax-rs 实现必须支持将实体主体映射到你的方法的参数。如果它不符合您的需求,您可以设置自定义提供程序。

当然,表单参数不是在 POST 请求中发送数据的唯一方式。

使用@FormParam

当您使用表单参数时,需要使用application/x-www-form-urlencoded来使用它们。 Android 中是否有 HTML 表格并不重要。您请求的 Content-Type header 应设置为 application/x-www-form-urlencoded.

对于这种情况,您的 JAX-RS 资源中会有如下内容:

@Path("/prog")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Res method(@FormParam("id") Integer id, @FormParam("name") String name) {
    ...
}

要使用上面定义的端点,您的请求应该是这样的:

POST /app/prog HTTP/1.1
Content-Type: application/x-www-form-urlencoded

id=1&name=Example

请注意,在这种情况下,不需要 Java class 包装您的参数来接收参数。

使用@BeanParam

如果您更喜欢使用 Java class 来包装您的参数,您可以使用以下内容:

public class Res {

    @FormParam("id")
    private Integer id;

    @FormParam("name")
    private String name;

    // Default constructor, getters and setters ommited
}

你的资源方法将是这样的:

@Path("/prog")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Res method(@BeanParam Res res) {
    ...
}

要使用上面定义的端点,您的请求应该是这样的:

POST /app/prog HTTP/1.1
Content-Type: application/x-www-form-urlencoded

id=1&name=Example

消耗JSON

而不是 application/x-www-form-urlencoded,您的端点可以消耗 application/json

为此,您的端点方法如下:

@Path("/prog")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Res method(Res res) {
    ...
}

根据您的 JSON 供应商,您的模型 class 可以像:

public class Res {

    private Integer id;

    private String name;

    // Default constructor, getters and setters ommited
}

并且 JSON 将在请求负载中发送 application/json 作为 Content-Type:

POST /app/prog HTTP/1.1
Content-Type: application/json

{
    "id": 1,
    "name": "Example"
}