我收到以下异常:
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
代码本身非常简单,此调用可在邮递员中进行。
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
}
}
答案 0 :(得分:0)
我最终通过旧的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;
}