首页 > 解决方案 > JAX-RS Jersey @BeanParam 无法处理“application/x-www-form-urlencoded”

问题描述

这是我要处理 POST 操作以获取的资源类@BeanParam

import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Component;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Path("")
@Component
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
public class MyResource{

    @POST
    @Path("/create")
    @ApiOperation()
    @ApiResponses()
    public String createProfile(@BeanParam final Person person) {
        // Person handling goes here....
    }
}

public class Person{

    @FormParam("name")
    private String name;

    @FormParam("designation")
    private String designation;

    // getters and setters...
}

从测试:

public void test(){
    final String uri = BASE_URI + "/create";

    // Here I am creating Person and converting it as json
    final String jsonInput = SimplePojoMapper.toJSON(person);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    final HttpEntity<String> entity = new HttpEntity<>(jsonInput, headers);
    final ResponseEntity<String> responseEntity 
            = this.restTemplate.postForEntity(uri, entity, String.class);
    LOGGER.info("HTTP RESPONSE " + responseEntity.getStatusCode());
}

但它Person具有所有空字段。

有什么办法可以用@BeanParam. 我不想使用@FormParamMultuvaluedMap出于某种原因。

标签: javaspring-bootjax-rs

解决方案


如果您的服务器期望它是一个表单,那么将有效负载作为 JSON 发送将无济于事。所以你可以使用类似的东西:

Form form = new Form();
form.param("name", "John");
form.param("designation", "Anything");

Client client = ClientBuilder.newClient();
Response response = client.target("http://example.com/foo")
                          .request().post(Entity.form(form));

推荐阅读