我是Java和创建API的新手。我试图简单地发出POST请求并返回特定值。这是我的代码:
@Service
@AllArgsConstructor
public class WebService {
private RestTemplate restTemplate;
private static final String PROJECT_URL = "http://localhost:8080/project";
public ResponseEntity<ProjectResponse> createProject(Project project) {
ResponseEntity<ProjectResponse> completeProject = restTemplate.postForEntity(PROJECT_URL, project, ProjectResponse.class);
System.out.println("Response body " + completeProject.getBody());
return completeProject;
}
}
ProjectResponse类仅具有:
@Data
@NoArgsConstructor
public class ProjectResponse {
private String id;
}
问题是idaøwaus返回为(id = null)。即使当我使用“字符串”而不是ProjectResponse时,一切正常,并且我看到ID已创建。因此,由于某种原因,将响应映射到ProjectResponse类存在问题。
有人知道怎么了吗?
答案 0 :(得分:0)
尝试一下,使您的projectPesponse类与project相同。
@Service
@AllArgsConstructor
public class WebService {
private RestTemplate restTemplate;
private static final String PROJECT_URL = "http://localhost:8080/project";
public ResponseEntity<Project> createProject(Project newProject) {
Project completeProject = restTemplate.postForObject(PROJECT_URL, newProject, Project.class);
log("Response body " + completeProject.getBody());//Log this instead
return ResponseEntity.ok(completeProject);
}
}
答案 1 :(得分:0)
尝试此操作并在此处处理异常,以创建类ResponseErrorHandler并实现ResponseErrorHandler(i)
@Component
public class WebService {
private RestTemplate restTemplate;
private static final String PROJECT_URL = "http://localhost:8080/project";
public ProjectResponse createProject(Project project) {
ProjectResponseErrorHandler errorHandler = new ProjectResponseErrorHandler(
project.getId());
restTemplate.setErrorHandler(errorHandler);
ResponseEntity<ProjectResponse> completeProject = restTemplate.postForEntity(PROJECT_URL, project, ProjectResponse.class);
log("Response body " + completeProject.getBody());
return completeProject.getBody();
}
}