簡體   English   中英

使用Spring向一個API發出發布請求

[英]Make a post request from one api to another using spring

我有一個使用某些憑據登錄用戶的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);
    }

}

當用戶嘗試使用此方法進行身份驗證時,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;

}

日志網址是該方法在我的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;
}

}

當我調試時,當我執行對restTemplate.postForObject的調用時,程序停止。

觀察:String響應=“ Welcome to javainuse” + new Date(); 在我的log方法上僅用於測試,我想要的是在發布請求的正文上顯示消息,但是現在我只希望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>

並與郵遞員檢查您的第二個控制器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM