在开始下载之前,请检查服务器上是否存在位图



早上好, 我有以下代码从服务器下载 bitmpa。

/*SAVE IMAGE++++++++++++++++++++*/
public void saveImage(Context context, Bitmap b, String imageName) {
FileOutputStream foStream;
try {
foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG, 100, foStream);
foStream.close();
UPDTV_FOTO.setBackgroundColor(Color.GREEN);
image.setImageBitmap(loadImageBitmap(getApplicationContext(), Giocatore));
UPDTV_FOTO.setText("Download "+Giocatore+ " Complete");
}  
catch (FileNotFoundException e) { 
Log.d("saveImage", "file not found"); 
e.printStackTrace();
//   UPDTV_FOTO.setText("FILE NOT FOUND");
}  
catch (IOException e) { 
Log.d("saveImage", "io exception"); 
e.printStackTrace();
//  UPDTV_FOTO.setText("SAVE IMAGE ERROR");
} 
}
/*SAVE IMAGE+++++++++++++++++++++++++*/     

/*DOWNLOAD IMAGE++++++++++++++++++++++*/
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
private String TAG = "DownloadImage";
private Bitmap downloadImageBitmap(String sUrl) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(sUrl).openStream();   // Download Image from URL
bitmap = BitmapFactory.decodeStream(inputStream);       // Decode Bitmap
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "Exception 1, Something went wrong!");
e.printStackTrace();
//  UPDTV_FOTO.setText("DOWNLOAD ERROR");
}
return bitmap;
}
@Override
protected Bitmap doInBackground(String... params) {
return downloadImageBitmap(params[0]);
}
protected void onPostExecute(Bitmap result) {
saveImage(getApplicationContext(), result, Giocatore);
}
}
/*DOWNLOAD IMAGE++++++++++++++++++++++*/        

/*LOAD IMAGE*+++++++++++++++++++++++++++++++++++++*/
public Bitmap loadImageBitmap(Context context, String imageName) {
Bitmap bitmap = null;
FileInputStream fiStream;
try {
fiStream    = context.openFileInput(imageName);
bitmap      = BitmapFactory.decodeStream(fiStream);
fiStream.close();
} catch (Exception e) {
Log.d("saveImage", "Exception 3, Something went wrong!");
e.printStackTrace();
//  UPDTV_FOTO.setText("LOAD ERROR");
}
return bitmap;
}
/*LOAD IMAGE+++++++++++++++++++++++++++*/

如果我尝试下载的位图在服务器上可用,则一切正常

new DownloadImage().execute(myurl);

否则,如果不可用,我的应用程序将崩溃。 所以我想在开始下载之前检查一下服务器上是否有位图可用。

我尝试

if (URLUtil.isValidUrl(URL+FotoGiocatore)==true);

还有

如何以编程方式测试 HTTP 连接?

使用其 URL 检查远程服务器上是否存在文件

您还可以使用以下代码来检查图像是否存在

URL url = new URL("YOUR URL");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
`int status = urlConnection.getResponseCode();` 

并且仅在以下情况下开始下载status==200

相关内容

最新更新