0

Till this date my app was using the images from an http site and the site is now being upgraded to https . So here comes the issue, now my app does not shows the images at al even though my url is updated. Please look at my current code and help me.

Thanks, Yoga.

Code:

public class MainActivity extends Activity {

public static final String URL =
    "https://googledrive.com/host/0B_DiX4MiMa3HTHdiYVRmUHBMcW8/image1.jpg";
ImageView imageView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    imageView = (ImageView) findViewById(R.id.ImageView1);

    // Create an object for subclass of AsyncTask
    GetXMLTask task = new GetXMLTask();
    // Execute the task
    task.execute(new String[] { URL });
}

private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... urls) {
        Bitmap map = null;
        for (String url : urls) {
            map = downloadImage(url);
        }
        return map;
    }

    // Sets the Bitmap returned by doInBackground
    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
        System.out.println("finished");
    }

    // Creates Bitmap from InputStream and returns it
    private Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.
                    decodeStream(stream, null, bmOptions);
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }

    // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException {
        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpsURLConnection httpConnection = (HttpsURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stream;
    }
}

}

Yogamurthy
  • 988
  • 15
  • 22

2 Answers2

0

use HttpsURLConnection instead of HttpURLConnection for https connections


Update: I just checked the url of your image and it returned status 304 instead 200

Request URL:https://googledrive.com/host/0B_DiX4MiMa3HTHdiYVRmUHBMcW8/image1.jpg Request Method:GET Status Code:304 Not Modified

==> Try handling the status HTTP_NOT_MODIFIED instead of HTTP_OK. Or just handle both cases:

if (httpConnection.getResponseCode() == HttpsURLConnection.HTTP_OK ||
    httpConnection.getResponseCode() == HttpsURLConnection.HTTP_NOT_MODIFIED ) {

      stream = httpConnection.getInputStream();
} else { // just in case..
      log.wtf("Surprize!", "HTTP status was: " + httpConnection.getResponseCode());
}

see documentation about http status 304 Not Modified:

If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.

donfuxx
  • 11,277
  • 6
  • 44
  • 76
  • 1
    will give a try and let you know the result in a while – Yogamurthy Mar 15 '14 at 08:38
  • It dint work @donfuxx. Please see my updated code and let me know what else needs to be updated – Yogamurthy Mar 15 '14 at 08:44
  • Did you also try the handling the http 304 like in the update? – donfuxx Mar 15 '14 at 09:12
  • yes. just now tried and this too doesnt seem to work... is thre any other way to get image from https site – Yogamurthy Mar 15 '14 at 09:15
  • log the value of `httpConnection.getResponseCode()` like in my updated answer. Maybe Google Drive blocks requests that are not from a browser – donfuxx Mar 15 '14 at 09:18
  • log says "03-15 09:40:43.034: I/System.out(1842): Surprize0!HTTP status was:org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl$LimitedInputStream@43e9b3a8 " – Yogamurthy Mar 15 '14 at 09:42
  • OK, I put wrong output in log message. Try again with `log.wtf("Surprize!", "HTTP status was: " + httpConnection.getResponseCode());` to see the status code actually. – donfuxx Mar 15 '14 at 09:49
  • http status was : 200 – Yogamurthy Mar 15 '14 at 09:58
  • Lol that is weird. In theory if http status is 200 then the else block should not have been executed.. and if I open your image in browser I see http status 304. – donfuxx Mar 15 '14 at 10:05
  • yeah.it is rattling my head. planning to use webview instead of all these stuffs – Yogamurthy Mar 15 '14 at 10:23
0
  {

     trustEveryone();
    // UNIVERSAL IMAGE LOADER SETUP
    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheOnDisc(true).cacheInMemory(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .displayer(new FadeInBitmapDisplayer(300)).build();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
            getApplicationContext())
            .defaultDisplayImageOptions(defaultOptions)
            .memoryCache(new WeakMemoryCache())
            .discCacheSize(100 * 1024 * 1024).build();

    ImageLoader.getInstance().init(config);

    //your image url
    String url = "https://thepoprewards.com.au/uploads/user_image/1514370542.jpg";

    ImageLoader imageLoader = ImageLoader.getInstance();
    DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisc(true).resetViewBeforeLoading(true)
            .build();


    imageLoader.displayImage(url, img, options);
}

After write this code now write the method trustEveryone

  private void trustEveryone() {
    try {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }});
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[]{new X509TrustManager(){
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {}
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {}
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }}}, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(
                context.getSocketFactory());
    } catch (Exception e) { // should never happen
        e.printStackTrace();
    }
}