2015-01-04 109 views
0

我想在我的android应用程序中从网下载图像,它工作大部分时间,但一些图片无法下载,位图为空。然而,图像的链接总是在那里。任何想法是什么造成这种情况?Android-下载图片偶尔会失败。

 private class GetImage extends AsyncTask<String, Void, String> { 
      @Override 
      protected String doInBackground(String... urls) { 

       int len = 500; 

       try { 
        URL url = new URL(urls[0]); 
        Log.v("url",urls[0]); 
        HttpURLConnection connection = (HttpURLConnection) url 
          .openConnection(); 
        connection.setReadTimeout(10000); 
        connection.setConnectTimeout(15000); 
        connection.setRequestMethod("GET"); 
        connection.setDoInput(true); 

        connection.connect(); 
        int response = connection.getResponseCode(); 

        inputstream = connection.getInputStream(); 
        System.out.println(inputstream.toString()); 

        bitmap = BitmapFactory.decodeStream(inputstream); 
        if(bitmap==null) 
         Log.v("Bitmap","fail"); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } finally { 
        if (inputstream != null) { 
         try { 
          inputstream.close(); 
         } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
        } 
       } 
       return "some string since it bitmap is sometimes null"; 

回答

0

你不能总是依靠网络。你可以使用像okhttp或volley这样的http库,这将允许你轻松地重试(或者你可以重试自己)。这些库通过使用原始HttpUrlConnection来完成一系列操作来消除http体验。

根据图像的严重程度,如果失败,您可以将图像隐藏在onPostExecute中。

+0

不,它是每次相同的图像,如果我改变它的图像工作正常。 现在我无法重试其他图书馆,截止日期很近。 – 2015-01-04 12:27:12

+0

尽管它与所有其他JPG一样 – 2015-01-04 12:30:03

+0

当您尝试下载这些图像时,是否会收到特定的例外情况? – 2015-01-04 21:59:17