JAX-RS球衣@BeanParam无法处理“ application / x-www-form-urlencoded”

时间:2018-08-15 16:31:27

标签: java spring-boot jax-rs

这是我的Resource类,我要在其中处理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

1 个答案:

答案 0 :(得分:0)

如果服务器期望有效载荷为表单,则将有效载荷作为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));