gpt4 book ai didi

android - 通过循环泄漏数据

转载 作者:搜寻专家 更新时间:2023-11-01 09:45:58 27 4
gpt4 key购买 nike

我正在尝试通过 AsyncTask 下载网页的 html,然后在日志中显示该 html。

这是我的代码。但是,当我运行代码时,循环永远不会停止。

public class MainActivity extends AppCompatActivity {

public class DownloadTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... urls) {

String result = "";
HttpURLConnection connection = null;
URL myUrl;

try{
myUrl = new URL(urls[0]);
connection = (HttpURLConnection) myUrl.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);

int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch(Exception e){
e.printStackTrace();
return "Failed";
}
}
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

DownloadTask task = new DownloadTask();
try {
String result = task.execute("http://www.posh24.com/celebrities").get();
Log.i("asd",String.valueOf(result));
}
catch(Exception e){
e.printStackTrace();
}
}
}

我的日志充满了:

D/dalvikvm: GC_FOR_ALLOC freed 297K, 20% free 2582K/3200K, paused 4ms, total 4ms

知道代码有什么问题吗?

最佳答案

你的代码的问题是 data 在你用一个 read() 调用初始化它之后不会改变,所以它永远不会是 -1(因此无限循环)。

您需要在循环内调用read()

替换以下内容:

int data  = reader.read();
while(data != -1){
// ...

像这样:

int data;
while ((data = reader.read()) != -1) {
// ...

为了加快速度,您可以使用 BufferedReader:

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String line = null;
StringBuilder builder = new StringBuilder();

while((line = reader.readLine()) != null) {
builder.append(line);
}

String data = builder.toString();

关于android - 通过循环泄漏数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38106472/

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