我正在尝试在应用程序的其他模块中访问 Spring REST 端点。所以我尝试使用 REST 模板来获取用户列表,如下所示:
使用 REST 模板的 API 请求:
public List<LeadUser> getUsersBySignUpType(String type, String id) {
String adminApiUrl = adminApiBaseUrl+"/crm/v1/users/?type="+type+"&id="+id;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<LeadUserList> response = restTemplate.exchange(
adminApiUrl, HttpMethod.GET, entity, LeadUserList.class);
return response.getBody().getUsersList();
}
LeadUserList 类:
public class LeadUserList {
private List<LeadUser> usersList;
public List<LeadUser> getUsersList() {
return usersList;
}
}
LeadUser 模型类:
public class LeadUser {
@JsonProperty("id")
private String id;
@JsonProperty("email")
private String email;
@JsonProperty("name")
private String name;
@JsonProperty("businessName")
private String businessName;
@JsonProperty("phone")
private String phone;
@JsonProperty("address")
private String address;
@JsonProperty("createdTime")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date createdTime;
@JsonProperty("updatedTime")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date updatedTime;
@JsonProperty("bookletSignups")
private BookletSignUp bookletSignUp;
@JsonProperty("eventSignups")
private EventSignUp eventSignUp;
@JsonProperty("infoSignups")
private InfoSignUp infoSignUp;
@JsonProperty("webinarSignups")
private WebinarSignUp webinarSignUp;
public LeadUser() {
}
}
API端点 Controller 类:
@Controller
@Component
@RequestMapping(path = "/crm/v1")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value = "/users", method = GET,produces = "application/json")
@ResponseBody
public ResponseEntity<List<User>> getPartnersByDate(@RequestParam("type") String type,
@RequestParam("id") String id) throws ParseException {
List<User> usersList = userService.getUsersByType(type);
return new ResponseEntity<List<User>>(usersList, HttpStatus.OK);
}
}
虽然来自 API 端点的返回类型是 JSON,但我得到了上述异常。我在这里做错了什么?
异常(exception):
Could not extract response: no suitable HttpMessageConverter found for response type [class admin.client.domain.LeadUserList] and content type [application/json]
最佳答案
尝试如下其他设置,
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
同时修复您的交换调用,
ResponseEntity<List<LeadUser>> response = restTemplate.exchange(
adminApiUrl, HttpMethod.GET, entity, new ParameterizedTypeReference<List<LeadUser>>(){});
关于java - 未找到适合响应类型和内容类型 [application/json;charset=UTF-8] 的异常的 HttpMessageConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55921261/