我希望在Log中显示URL的内容。但问题是这段代码没有将任何数据存储到onCreate方法的字符串变量 result 中,而不显示在日志中。
有什么建议吗?
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+=result;
data=reader.read();
}
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("Success","Till here worked");
DownloadTask task = new DownloadTask();
String result=" ";
Log.i("Success","Till here worked");
try {
Log.i("Success","Till here worked");
result = task.execute("https://www.google.com").get();
Log.i("Success","Till here worked");
Log.i("Content of URL : ",result);
Log.i("Failure","No result before this");
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
您错过了异步执行的行为。DownloadTask
将在单独的线程上启动,MainThread将按顺序运行代码。所以这样result
每次都会为空。
所以onPostExecute()
AsyncTask
内的内容也是如此。了解AsyncTask的工作情况。
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 += result;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Log.i("Content of URL : ", result);
// USe the result for further process here
} else {
Log.i("Failure", "No result");
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("https://www.google.com");
}
答案 1 :(得分:0)
使用排球库从网址获取内容。