我想下载一个网站并将内容作为字符串显示在日志中,但首先应用程序需要几个小时才能加载,如果加载,我就不会获得该网站的源代码。
public class MainActivity extends AppCompatActivity {
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.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();
String result = null;
try {
result = task.execute("http://www.kicker.de/").get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.i("Contents of URL", result);
}
}
答案 0 :(得分:0)
您应该使用BufferedReader来获取从InputStreamReader
读取的实际数据{{1}}
}