使用Asynctask下载Web内容

时间:2016-08-10 06:33:07

标签: android-studio android-asynctask download

我创建了这个用于下载Web内容的代码,我使用了Asynctask,但是DownloadTask类没有返回结果。但是,当我在这个课程中登录时,它会显示网站的内容。因此DownloadTask课程会下载内容,但不会返回内容!

这是我的代码:

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

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 result;    

}
    }

    @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.stackoverflow.com").get();
} catch (InterruptedException e) {
            e.printStackTrace();
} catch (ExecutionException e) {
            e.printStackTrace();
}

        Log.i("Log", "Result ...>>>>>>>" + result);
}
}

4 个答案:

答案 0 :(得分:1)

您的代码正确,但是您必须添加连接互联网的权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.waleed.downloadtask">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

答案 1 :(得分:1)

//此替代方法对我有用。尝试以下代码

BufferedReader br = new BufferedReader(reader);
String inputLine;

while ((inputLine = br.readLine()) != null)
result += inputLine;
in.close();

//而不是

int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();}

答案 2 :(得分:0)

您是否在“清单”中添加了访问Internet的权限?     

while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
            return result;
}
        catch (Exception e) {
            e.printStackTrace();
}
        return Null;       // This one should return null or something else if you 
didnt get a proper  url 

}
}

答案 3 :(得分:0)

首先确保设备已连接到互联网。否则,日志将显示错误 未知主机异常由于您的设备未连接到Internet。并且无法从Internet下载内容。您的设备应连接到Internet。 然后尝试以下代码 `

});
oktaSignIn.renderEl(
    { el: '#okta-login-container' },
    function (res) {
    if (res.status == 'SUCCESS') {
            alert("User successfully authenticated");
            console.log(res);*/
            $location.path("https://www.google.com/");



    }
);

enter image description here