簡體   English   中英

當 API 響應返回 Java 中的 null 正文時如何處理?

[英]How to handle case when API response returns a null body in Java?

我正在使用 POST 方法調用文件服務器的 REST API 並將其發送要上傳的文件內容。 REST API 應該理想地保存文件並發送包含文件名的響應。 我的代碼是這樣的。

public String uploadFile() {
    UploadResponse response = restTemplate.postForObject(
            FILE_SERVER_URL/upload,
            new HttpEntity<>(fileContent, headers),
            UploadResponse.class);
    return response.getFileName();
}

在上面的代碼中,編譯器抱怨UploadResponse response可能是 null,我應該處理它。 我打算用下面的代碼來處理它。

public String uploadFile() {
    UploadResponse response = restTemplate.postForObject(
            FILE_SERVER_URL/upload,
            new HttpEntity<>(fileContent, headers),
            UploadResponse.class);
    if(response != null) {
            return response.getFileServiceId();
        }
        else {
            throw new RuntimeException("File upload failed");
        }
}

但是,我不確定這是否是處理此問題的正確方法。 我不覺得這是一個運行時異常。 請指導我如何處理響應可能是 null 的情況。

您可以使用 Optional 來避免代碼中的 null 檢查。

你可以在這里閱讀這個非常有見地的問答 - https://softwareengineering.stackexchange.com/questions/309134/why-is-using-an-optional-preferential-to-null-checking-the-variable

暫無
暫無

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

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