我有一个 API 可以使用一些凭据登录用户,我正在开发另一个 API 来注册程序日志。
基本上我想在我的方法上调用另一个 api。
这是我现在的代码,但我总是得到 500 空错误:
这是我 Controller 上的登录方法:
@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);
}
}
当用户尝试验证自己时,此方法 this.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;
}
日志 url 是该方法在我的 loggerAPI 上的路径:
interservice.logs.endpoint=http://localhost:8084/logs/success
这是我的日志 Controller :
@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;
}
当我调试程序时,当我调用 restTemplate.postForObject 调用时程序停止。
观察:String response = "Welcome to javainuse "+ new Date();我的日志方法仅用于测试,我想要的是在发布请求的正文中显示消息,但现在我只希望 API 之间的连接正常工作。
最佳答案
试试这个。
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 检查您的第二个 Controller
关于java - 使用 spring 从一个 api 向另一个 api 发出发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55747112/