当前位置: 首页 > 知识库问答 >
问题:

未找到响应类型和内容类型[application/json;charset=UTF-8]异常的合适HttpMessageConverter

黄弘深
2023-03-14

我试图在应用程序的另一个模块中访问SpringRESTendpoint。因此,我尝试使用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() {
    }
}

APIendpoint控制器类:

@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);
    }
}

尽管返回类型是来自APIendpoint的JSON,但我得到了上述异常。我做错了什么?

例外情况:

Could not extract response: no suitable HttpMessageConverter found for response type [class admin.client.domain.LeadUserList] and content type [application/json]

共有1个答案

颜博达
2023-03-14

请尝试以下附加设置,

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>>(){});
 类似资料: