gpt4 book ai didi

Java声明对象但在 'if'内分配它是行不通的

转载 作者:行者123 更新时间:2023-12-01 09:35:23 25 4
gpt4 key购买 nike

我声明一个这样的对象:

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 方法来自 OkHttp3 java 库。

更新:

在第一个代码中的 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().

另请参阅此答案:https://stackoverflow.com/a/32307866/1371329

关于Java声明对象但在 'if'内分配它是行不通的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com