为什么我的图片没有从android的URL下载?
我正在尝试使用为什么我的图片没有从android的URL下载?,android,Android,我正在尝试使用URL下载/检索图像,并将其保存在sdcard中。我使用了以下代码,但我的图像文件是空白的。谁能告诉我该一步一步地做什么,或者我错在哪里。我的代码如下: URL url = new URL("http://www.mydomainname.com/task/uploads/test2.png"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConne
URL
下载/检索图像,并将其保存在sdcard
中。我使用了以下代码,但我的图像文件是空白的。谁能告诉我该一步一步地做什么,或者我错在哪里。我的代码如下:
URL url = new URL("http://www.mydomainname.com/task/uploads/test2.png");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
String filename= "downloadedFile.png";
Log.i("Local filename:",""+filename);
File file = new File(SDCardRoot,filename);
if(file.createNewFile())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize)
filepath=file.getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// filepath=null;
e.printStackTrace();
}
为什么不使用图像加载库呢。它将在一行代码中从给定URL加载图像,并管理所有与图像加载相关的任务,如缓存、内存管理、asyn任务等 例如,只需使用这个很棒的图像加载库: 1.) 只需要一行代码就可以完成所有任务
Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
您还可以将图像保存到sd卡。请查看我的答案,这对我来说很有用 请在您的清单文件中提及以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
请参考此代码
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import com.google.android.gms.internal.dw;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class DownLoadImage extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_main);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... arg0) {
Bitmap bitmap = DownloadImage(
"http://www.yourdomainname.com/imgs/arrangemen4.jpg");
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/MyApp");
if (!mFolder.exists()) {
mFolder.mkdir();
}
String strF = mFolder.getAbsolutePath();
File mSubFolder = new File(strF + "/MyApp-SubFolder");
if (!mSubFolder.exists()) {
mSubFolder.mkdir();
}
String s = "myfile.png";
File f = new File(mSubFolder.getAbsolutePath(),s);
String strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);
fos.flush();
fos.close();
// MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
Toast.makeText(DownLoadImage.this, "Done", Toast.LENGTH_SHORT).show();
};
}.execute();
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.URLConnection;
导入com.google.android.gms.internal.dw;
导入android.app.Activity;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.Environment;
导入android.widget.Toast;
公共类DownLoadImage扩展活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.action_main);
新建异步任务(){
@凌驾
受保护的Void doInBackground(Void…arg0){
位图位图=下载图像(
"http://www.yourdomainname.com/imgs/arrangemen4.jpg");
字符串extr=Environment.getExternalStorageDirectory().toString();
File mFolder=新文件(extr+“/MyApp”);
如果(!mFolder.exists()){
mkdir();
}
字符串strF=mFolder.getAbsolutePath();
File mSubFolder=新文件(strF+“/MyApp子文件夹”);
如果(!mSubFolder.exists()){
mSubFolder.mkdir();
}
字符串s=“myfile.png”;
文件f=新文件(mSubFolder.getAbsolutePath(),s);
字符串strMyImagePath=f.getAbsolutePath();
FileOutputStream=null;
试一试{
fos=新文件输出流(f);
压缩(bitmap.CompressFormat.PNG,70,fos);
fos.flush();
fos.close();
//MediaStore.Images.Media.insertImage(getContentResolver(),b,“Screen”,“Screen”);
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
受保护的void onPostExecute(void结果){
Toast.makeText(DownLoadImage.this,“Done”,Toast.LENGTH_SHORT.show();
};
}.execute();
}
私有InputStream OpenHttpConnection(字符串urlString)
抛出IOException
{
InputStream in=null;
int响应=-1;
URL=新URL(URL字符串);
URLConnection conn=url.openConnection();
if(!(HttpURLConnection的连接实例))
抛出新IOException(“非HTTP连接”);
试一试{
HttpURLConnection httpConn=(HttpURLConnection)conn;
httpConn.setAllowUserInteraction(假);
httpConn.setInstanceFollowRedirects(真);
httpConn.setRequestMethod(“GET”);
httpConn.connect();
response=httpConn.getResponseCode();
if(response==HttpURLConnection.HTTP\u OK){
in=httpConn.getInputStream();
}
}
捕获(例外情况除外)
{
抛出新IOException(“连接错误”);
}
返回;
}
私有位图下载图像(字符串URL)
{
位图=空;
InputStream in=null;
试一试{
in=OpenHttpConnection(URL);
位图=BitmapFactory.decodeStream(in);
in.close();
}捕获(IOE1异常){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
返回位图;
}
}
谢谢……)
如果您有任何问题,请尽管问我……到底是什么不起作用?有错误日志吗?定义“空白图像”。为什么不使用DownloadManager?给定url上没有图像:)我的SD卡中有downloadedFile.png,但它是一个没有图像的空白文件。因此,我猜图像没有从URL下载。如果引发任何异常,请检查stacktrace。如果添加了Internet权限,请检查您的权限?