#java #resttemplate
#java #resttemplate
Вопрос:
Я получаю следующее исключение: ERROR [tomcat-http--39] (Controller.java:193) - Could not read [class java.lang.String]; nested exception is org.springframewor
k.oxm.UnmarshallingFailureException: XStream unmarshalling exception; nested exception is com.thoughtworks.xstream.mapper.CannotResolveCl
assException: response : response
Сам код довольно прост, и этот вызов работает в postman.
private boolean insertContactInSilverpop(String email, String token) throws ClientProtocolException, IOException {
final String url = "https://api1.silverpop.com:443/rest/databases/...";
String requestJson = new StringBuilder("{"email":"")
.append(email)
.append("","emailType":"HTML","leadSource":"internal pop-up","optInDetails":"User Name: name, IP Address: 0.0.0.0"}")
.toString();
final HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " token);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> result = null;
try {
result = restTemplate.postForEntity(url, entity, String.class);
return result.getStatusCode() == HttpStatus.CREATED;
}catch(Exception e){
e.printStackTrace();
log.error(e.getLocalizedMessage());
return false;
}
}
Он успешно вставляет данные, но при этом выдает исключение.
РЕДАКТИРОВАТЬ: добавление ответа api:
{
"meta": {
"attributes": {},
"generalErrors": [],
"fieldErrors": {},
"links": [],
"nextPageUrl": null
},
"data": {
"location": "https://api1.silverpop.com/rest/databases/111/contacts/123",
"id": 123
}
}
Комментарии:
1. Не могли бы вы также вставить ответ API, как показано в (рабочем) postman? Также конфигурация spring, в которой вы определили какие-либо преобразователи HTTP-сообщений или нет?
Ответ №1:
В итоге я сделал это с помощью старого метода HttpURLConnection, и это сработало. На всякий случай, если кто-то столкнется с этим, вот мое решение:
private boolean insertContactInSilverpop(String email, String tokenSp) throws ClientProtocolException, IOException {
final String urlStr = "https://api1.silverpop.com:443/rest/databases/111/contacts";
String requestJson = new StringBuilder("{"email":"").append(email)
.append("","emailType":"HTML","leadSource":"internal pop-up","optInDetails":" IP Address: 0.0.0.0"}").toString();
byte[] postDataBytes = requestJson.getBytes("UTF-8");
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " tokenSp);
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setUseCaches(false);
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postDataBytes);
}
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char) c);
String response = sb.toString();
log.info(response);
int code = conn.getResponseCode();
return code == 201;
}