Java 声明对象但在 'if' 内分配它不起作用

Java declare object but assign it inside 'if' won't work

我正在这样声明一个对象:

Response getMessagesResponse;
        if (page == 0) {
            getMessagesResponse = myRequest.newCall(getMessagesRequest).execute();
            System.out.println("response "+getMessagesResponse.body().string());

无论我 运行 多少次,上面的代码都会打印一个空字符串。现在,如果我在同一行分配和调用对象,如下所示:

if (page == 0) {
            Response a = sisgradRequest.newCall(getMessagesRequest).execute();
            System.out.println("response "+a.body().string());

它会起作用的。为什么?我一直在 java 中做这样的事情并且没有问题。这里的newCall方法来自OkHttp3java库

更新:

在第一个代码中的 System.out.println() 之前,我有这一行:

        this.magicalNumber = getMagicalNumber(getMessagesResponse.body().string());

结果是,如果我在它前面加上 System.out.println(),我就能打印出来。如果我把它放在后面,我不明白。为什么?也许是因为 getMagicalNumber 中的 jSoup 处理了数据,然后从主对象中删除了它?

正如@Taylor 评论的那样,ResponseBody 是一个只能使用一次的流。来自documentation,

The response body can be consumed only once.

This class may be used to stream very large responses. For example, it is possible to use this class to read a response that is larger than the entire memory allocated to the current process. It can even stream a response larger than the total storage on the current device, which is a common requirement for video streaming applications.

Because this class does not buffer the full response in memory, the application may not re-read the bytes of the response. Use this one shot to read the entire response into memory with bytes() or string(). Or stream the response with either source(), byteStream(), or charStream().

另请参阅此答案: