java - 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
. 我不想使用@FormParam
或MultuvaluedMap
出于某种原因。
解决方案
如果您的服务器期望它是一个表单,那么将有效负载作为 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));
推荐阅读
- python - 如何在 tensorflow 中实现负二项式可能的 hood 函数并将其用作损失函数来训练 RNN?
- javascript - 如何从循环中执行总和?
- java - How to connect to dynamodb from lambda
- firebase-cloud-messaging - 如果用户安装了我的 PWA,我是否需要单独请求权限才能发送推送通知?
- ide - 用于 PHP 扩展开发的 CLion?
- sql-server - Merge rows in single SQL table
- ruby-on-rails - Delete a user together with his posts
- c - C align columns w/ printf() w/ exactly 2 spaces after each column
- android - Android SharedPreferences 数据没有被保存(或者我没有正确检索它)?
- laravel - Laravel Image Resize Problem (image-intervention)