天天看點

關于Imageloader加載https安全連結

鄙人不才,圖個安逸,也沒接觸到什麼新的知識,接着上邊兩個部落格的講述,講解一下關于ImageLoader加載https連結的過程。對于初學者來說,确實能夠起到一定的幫助作用。

  • 相信大家在開發app過程中,肯定會接觸到第三方加載圖檔工具(比如Glide,ImageLoader,vollery,xutils等等)
  1. Glide這裡不做講解,自己也沒怎麼用過,詳情可以了解郭霖的部落格 https://blog.csdn.net/guolin_blog/。
  2. vollery架構,部落客也沒使用過,xutils光聽說過,也沒用過。
  3. 現在隻能講解Imageloader的加載呢。
  •        ImageLoader簡介

                 ImageLoader是一個加載圖檔的開源架構,其基本功能為加載本地和網絡圖檔。

                 github位址:https://github.com/nostra13/Android-Universal-Image-Loader

                 詳細了解可以從此連結進入:https://blog.csdn.net/wl1769127285/article/details/52786717

  •       ImageLoader 使用

             在後來的版本中省去了初始化的過程,可以直接使用

             下邊介紹其主流的幾個方法:

  1.          displayImage
    /**
    	 * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br />
    	 * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call
    	 *
    	 * @param uri       Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png")
    	 * @param imageView {@link ImageView} which should display image
    	 * @param options   {@linkplain DisplayImageOptions Display image options} for image displaying. If <b>null</b> -
    	 *                  default display image options
    	 *                  {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from
    	 *                  configuration} will be used.
    	 * @throws IllegalStateException    if {@link #init(ImageLoaderConfiguration)} method wasn't called before
    	 * @throws IllegalArgumentException if passed <b>imageView</b> is null
    	 */
    	public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) {
    		displayImage(uri, imageView, options, null);
    	}
               

 loadImage

/**
	 * Adds load image task to execution pool. Image will be returned with
	 * {@link ImageLoadingListener#onLoadingComplete(String, android.view.View, android.graphics.Bitmap)} callback}.<br />
	 * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call
	 *
	 * @param uri          Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png")
	 * @param minImageSize Minimal size for {@link Bitmap} which will be returned in
	 *                     {@linkplain ImageLoadingListener#onLoadingComplete(String, android.view.View, android.graphics.Bitmap)} callback}. Downloaded image will be decoded
	 *                     and scaled to {@link Bitmap} of the size which is <b>equal or larger</b> (usually a bit larger) than
	 *                     incoming minImageSize .
	 * @param listener     {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on UI
	 *                     thread.
	 * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before
	 */
	public void loadImage(String uri, ImageSize minImageSize, ImageLoadingListener listener) {
		loadImage(uri, minImageSize, null, listener);
	}
           
  •  上邊ImageLoader的方法簡單介紹了一下,回歸正題:imageload加載https圖檔
關于Imageloader加載https安全連結

 如上圖所示:初始化的時候,隻需要引入一個附加元件 .imageDownloader()

附加元件裡邊的執行個體如下:

package com.nuctech.handheldlock.https;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;

import android.content.Context;

import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

public class AuthImageDownloader extends BaseImageDownloader {

	private SSLSocketFactory mSSLSocketFactory;

	public AuthImageDownloader(Context context) {
		super(context);
		SSLContext sslContext = sslContextForTrustedCertificates();
		mSSLSocketFactory = sslContext.getSocketFactory();
	}

	public AuthImageDownloader(Context context, int connectTimeout,
			int readTimeout) {
		super(context, connectTimeout, readTimeout);
		SSLContext sslContext = sslContextForTrustedCertificates();
		mSSLSocketFactory = sslContext.getSocketFactory();
	}

	@Override
	protected InputStream getStreamFromNetwork(String imageUri, Object extra)
			throws IOException {
		URL url = null;
		try {
			url = new URL(imageUri);
		} catch (MalformedURLException e) {
		}
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(connectTimeout);
		conn.setReadTimeout(readTimeout);

		if (conn instanceof HttpsURLConnection) {
			((HttpsURLConnection) conn).setSSLSocketFactory(mSSLSocketFactory);
			((HttpsURLConnection) conn).setHostnameVerifier((DO_NOT_VERIFY));
		}
		return new BufferedInputStream(conn.getInputStream(), BUFFER_SIZE);
	}

	// always verify the host - dont check for certificate
	final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};

	public SSLContext sslContextForTrustedCertificates() {
		javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
		javax.net.ssl.TrustManager tm = new miTM();
		trustAllCerts[0] = tm;
		SSLContext sc = null;
		try {
			sc = SSLContext.getInstance("SSL");
			sc.init(null, trustAllCerts, null);
			// javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} finally {
			return sc;
		}
	}

	class miTM implements javax.net.ssl.TrustManager,
			javax.net.ssl.X509TrustManager {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public boolean isServerTrusted(
				java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public boolean isClientTrusted(
				java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public void checkServerTrusted(
				java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}

		public void checkClientTrusted(
				java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}
	}
}
           

這樣初始化之後就可以直接調用了

  •  調用部分:

        ImageLoader imageLoader = ImageLoader.getInstance();

        imageLoader.displayImage(mImageUrl, mImageView,OptionsUtils.getHeadOptions());

繼續閱讀