Android Studio 中的 HttpURL Sonnection 问题,同时从互联网加载图像



我正在尝试从网址下载图像:"http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png 之后,我想在图像视图中显示它。但 HttpURL 中的错误不断发生

单击按钮(调用下载函数(时,它应该删除以前的图像并从 url 加载新图像

我尝试在模拟器上使用互联网,并且工作正常。 模拟器和我的电脑已连接到互联网。我也在AndroidMenifest中请求了权限。但没有什么能解决问题。

package com.example.web;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public class ImageDownloader extends AsyncTask<String,Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} catch (IOException e) {
e.printStackTrace();
Log.i("Error","Error encountered");
}
return null;
}

}
public void download(View view) {
imageView = findViewById(R.id.imageView3);
imageView.setImageResource(0);
ImageDownloader imageDownloader = new ImageDownloader();
try {
Bitmap bitmap = imageDownloader.execute("http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png").get();
imageView.setImageBitmap(bitmap);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

AndroidMenifest 中的权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

根据您的代码,我写下新的 只是用现有的替换它

public class MainActivity extends AppCompatActivity {
ImageView imageView;
public class ImageDownloader extends AsyncTask<String,Void, Bitmap> {
OutputStream output;
@Override
protected Bitmap doInBackground(String... strings) {
int count;
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
try {
URL url = new URL(strings[0]);
URLConnection conection = url.openConnection();
conection.connect();

int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "DownloadedFile" + ts + ".jpg");

byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
if (Math.min(cur, 100) > 98) {
try {
// Sleep for 5 seconds
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "n " + cur);
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;

}
public void download(View view) {
imageView = findViewById(R.id.imageView3);
imageView.setImageResource(0);
ImageDownloader imageDownloader = new ImageDownloader();
try {
Bitmap bitmap = imageDownloader.execute("http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png").get();
imageView.setImageBitmap(bitmap);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

}

如果要下载映像并存储在本地存储中,请使用以下代码。

在这里,我创建了一个下载文件从URL.class文件,这是我的AsyncTask,因此下载处理不会中断。

public DownloadFileFromURL(Context context) {
this.context = context;
}
protected void onPreExecute() {
super.onPreExecute();
Log.e(TAG, "onPreExecute: Download started");
}
@Override
protected String doInBackground(String... f_url) {
int count;
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();

int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "Your Folder Name" + ts + ".jpg");

byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
if (Math.min(cur, 100) > 98) {
try {
// Sleep for 5 seconds
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "n " + cur);
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}

现在在您的活动中或在需要时调用上面的文件。在调用此 AsyncTask 时,传递您的 URL 以下载图像。

new DownloadFileFromURL(context).execute("Your Download URL");

最新更新