我有一个使用某些凭据登录用户的API,并且我正在开发另一个注册程序日志的API。
基本上我想在我的方法上调用另一个api。
这是我现在拥有的代码,但是我总是得到500空错误:
这是我的控制器上的登录方法:
@RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Object authenticate(@RequestBody UserEntity user) {
logger.debug("Begin request UaaController.authenticate()");
try {
this.redirectLogs("log that I want to process", logs_url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UserEntity usr = authenticationService.authenticate(user.getName(), user.getPassword().getPassword());
if (usr == null) {
logger.debug("User could not be found when executing UaaController.authenticate()");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} else {
logger.debug("Executed UaaController.authenticate() successfully");
return UaaService.getPermissionsFromUser(usr);
}
}
当用户尝试使用此方法进行身份验证时,redirectLogs应该将消息发送到我的日志api并从中创建日志。
这是方法:
private Object redirectLogs(String body,String logs_url) throws IOException {
StringBuilder redirectUrl = new StringBuilder();
redirectUrl.append(logs_url);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(body, headers);
String response= restTemplate.postForObject(redirectUrl.toString(), entity, String.class);
return response;
}
日志网址是该方法在我的loggerAPI上的路径:
interservice.logs.endpoint=http://localhost:8084/logs/success
这是我的日志控制器:
@RestController("/logs")
public class Log {
private static final Logger LOG = Logger.getLogger(Log.class.getName());
@PostMapping("/success")
public String helloWorld() {
String response = "Welcome to javainuse " + new Date();
LOG.log(Level.INFO, response);
return response;
}
}
在Im调试中,当Im调用restTemplate.postForObject调用时,程序停止。
观察:字符串响应=“欢迎使用javainuse” + new Date();在我的log方法上只是为了测试,我想要的是在发布请求的正文上显示消息,但是现在我只希望API之间的连接正常工作。
答案 0 :(得分:0)
尝试一下。
private Object redirectLogs(String body) {
return Jsoup.connect("http://localhost:8084/logs/success")
.method(Connection.Method.POST)
.header("Content-Type", "application/json")
.requestBody(body)
.execute();
}
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.3</version>
</dependency>
然后使用postman
检查第二个控制器