【发布时间】:2016-04-14 07:55:15
【问题描述】:
我想构建一个小型 RESTful 服务,使用我创建的类 (MyObject) 的对象发送 PUT 请求,并获得仅包含状态的响应。
我的控制者:
@RestController
public class MyControler {
@RequestMapping(path = "/blabla/{id}", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<String> putMethod (@PathVariable("id") Long id,
@RequestBody MyObject t) {
/*todo*/
return new ResponseEntity<String>(HttpStatus.OK);
}
我的测试应用
@SpringBootApplication
public class App {
public String httpPut(String urlStr) {
MyObject myObject = new MyObject(p,p,....);
URI url = null;
HttpEntity<MyObject> requestEntity;
RestTemplate rest = new RestTemplate();
rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.APPLICATION_JSON);
headers.setAccept(list);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Content-Type", "application/json");
requestEntity = new HttpEntity<Transaction>(t, headers);
ResponseEntity<String> response =
rest.exchange(url, HttpMethod.PUT, requestEntity, MyObject.class);
return response.getStatusCode().getValue();
}
我收到了HttpClientErrorException: 400 Bad Request
我的错误在哪里?我想要的是让 Spring 自动序列化 MyObject。 MyObject 类正在实现可序列化。
我错过了什么?
}
【问题讨论】:
-
!!!上面发布的代码中的一个错误:requestEntity = new HttpEntity
(t, headers); t 是 myObject 对象 -
当你调用 rest.exchange(..) .. 时,url 仍然为空。
-
抱歉,忘记复制我正在初始化 URL 的行。到目前为止我找到的解决方案是手动编写类来将 MyObject 序列化为 JSON 并反序列化它。但我想知道是否有办法让 srping-boot 和 spring 模板仅通过注释来处理所有这些
-
你没有发送任何东西。您期望
MyObject类作为返回值,但您什么也没有发送(如果您发送的是Transaction对象,而不是MyObject。)。你也做了很多,Spring boot 已经配置了你只需要注入它们并创建一个RestTemplate的转换器。所以你的代码是复杂和错误的。
标签: json rest spring-boot resttemplate