Glide 网络请求

来源:互联网 发布:广东元擎网络培训骗局 编辑:程序博客网 时间:2024/06/05 01:51
  1. Glide 内部使用 HttpURLConnection 执行网络请求
public class HttpUrlFetcher implements DataFetcher<InputStream> {}private InputStream loadDataWithRedirects(URL url, int redirects, URL lastUrl,      Map<String, String> headers) throws IOException {    if (redirects >= MAXIMUM_REDIRECTS) {      throw new HttpException("Too many (> " + MAXIMUM_REDIRECTS + ") redirects!");    } else {      // Comparing the URLs using .equals performs additional network I/O and is generally broken.      // See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html.      try {        if (lastUrl != null && url.toURI().equals(lastUrl.toURI())) {          throw new HttpException("In re-direct loop");        }      } catch (URISyntaxException e) {        // Do nothing, this is best effort.      }    }    urlConnection = connectionFactory.build(url);    for (Map.Entry<String, String> headerEntry : headers.entrySet()) {      urlConnection.addRequestProperty(headerEntry.getKey(), headerEntry.getValue());    }    urlConnection.setConnectTimeout(timeout);    urlConnection.setReadTimeout(timeout);    urlConnection.setUseCaches(false);    urlConnection.setDoInput(true);    // Stop the urlConnection instance of HttpUrlConnection from following redirects so that    // redirects will be handled by recursive calls to this method, loadDataWithRedirects.    urlConnection.setInstanceFollowRedirects(false);    // Connect explicitly to avoid errors in decoders if connection fails.    urlConnection.connect();    // Set the stream so that it's closed in cleanup to avoid resource leaks. See #2352.    stream = urlConnection.getInputStream();    if (isCancelled) {      return null;    }    final int statusCode = urlConnection.getResponseCode();    if (statusCode / 100 == 2) {      return getStreamForSuccessfulRequest(urlConnection);    } else if (statusCode / 100 == 3) {      String redirectUrlString = urlConnection.getHeaderField("Location");      if (TextUtils.isEmpty(redirectUrlString)) {        throw new HttpException("Received empty or null redirect url");      }      URL redirectUrl = new URL(url, redirectUrlString);      // Closing the stream specifically is required to avoid leaking ResponseBodys in addition      // to disconnecting the url connection below. See #2352.      cleanup();      return loadDataWithRedirects(redirectUrl, redirects + 1, url, headers);    } else if (statusCode == -1) {      throw new HttpException(statusCode);    } else {      throw new HttpException(urlConnection.getResponseMessage(), statusCode);    }  }
  1. Glide 的线程池
public final class GlideExecutor extends ThreadPoolExecutor {}GlideExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTimeInMs, String name,      UncaughtThrowableStrategy uncaughtThrowableStrategy, boolean preventNetworkOperations,      boolean executeSynchronously, BlockingQueue<Runnable> queue) {    super(        corePoolSize,        maximumPoolSize,        keepAliveTimeInMs,        TimeUnit.MILLISECONDS,        queue,        new DefaultThreadFactory(name, uncaughtThrowableStrategy, preventNetworkOperations));    this.executeSynchronously = executeSynchronously;  } private static final class DefaultThreadFactory implements ThreadFactory {    private final String name;    @Synthetic final UncaughtThrowableStrategy uncaughtThrowableStrategy;    @Synthetic final boolean preventNetworkOperations;    private int threadNum;    DefaultThreadFactory(String name, UncaughtThrowableStrategy uncaughtThrowableStrategy,        boolean preventNetworkOperations) {      this.name = name;      this.uncaughtThrowableStrategy = uncaughtThrowableStrategy;      this.preventNetworkOperations = preventNetworkOperations;    }    @Override    public synchronized Thread newThread(@NonNull Runnable runnable) {      final Thread result = new Thread(runnable, "glide-" + name + "-thread-" + threadNum) {        @Override        public void run() {          android.os.Process.setThreadPriority(              android.os.Process.THREAD_PRIORITY_BACKGROUND              + android.os.Process.THREAD_PRIORITY_MORE_FAVORABLE);          if (preventNetworkOperations) {            StrictMode.setThreadPolicy(                new ThreadPolicy.Builder()                    .detectNetwork()                    .penaltyDeath()                    .build());          }          try {            super.run();          } catch (Throwable t) {            uncaughtThrowableStrategy.handle(t);          }        }      };      threadNum++;      return result;    }  }}
  1. 数据回调
 interface DataCallback<T> {    void onDataReady(@Nullable T data);    void onLoadFailed(Exception e);  }

链接:http://blog.csdn.net/u013510838/article/details/52143113

阅读全文
0 0
原创粉丝点击