String Stringifiedjson = new Gson().toJson(user);
Log.d("SpringAndroid", Stringifiedjson);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(new
MediaType("application", "json")));
HttpEntity <? > requestEntity = new HttpEntity < Object >
(Stringifiedjson, requestHeaders);
GsonHttpMessageConverter messageConverter = new GsonHttpMessageConverter();
List < HttpMessageConverter <? >> messageConverters =
new ArrayList < HttpMessageConverter <? >> ();
messageConverters.add(messageConverter);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(messageConverters);
try {
ResponseEntity<String> responseEntity = restTemplate.
exchange(url, HttpMethod.POST, requestEntity, String.class);
}
我收到400 Bad Request,但是当我在我的小提琴手中发送Stringifiedjson
时。我得到一个有效的response
。现在如何使用RestTemplate发布GSON对象
答案 0 :(得分:1)
我有同样的问题。我通过传递Object本身而不是包含该Object的JSON表示的String来解决它。
简而言之,我改变了:
String jsonObject = convertToJSON(myObject);
HttpEntity <? > requestEntity = new HttpEntity <String>
(jsonObject, requestHeaders);
要:
HttpEntity <? > requestEntity = new HttpEntity <MyObject>
(myObject, requestHeaders);
在这种情况下,MyObject是我想要在Controller的@RequestBody参数中捕获的java bean。
答案 1 :(得分:0)
我认为问题可能在于您的http请求标头 以下对我有用。
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);