1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.chromium.net;
7 import android.content.Context;
8 import android.util.Log;
10 import java.lang.reflect.Constructor;
11 import java.nio.channels.WritableByteChannel;
15 * A factory for {@link HttpUrlRequest}'s, which uses the best HTTP stack
16 * available on the current platform.
18 public abstract class HttpUrlRequestFactory {
19 private static final Object sLock = new Object();
21 private static final String TAG = "HttpUrlRequestFactory";
23 private static final String CHROMIUM_URL_REQUEST_FACTORY =
24 "org.chromium.net.ChromiumUrlRequestFactory";
26 private static HttpUrlRequestFactory sFactory;
28 private static HttpUrlRequestFactory getFactory(
30 synchronized (sLock) {
31 if (sFactory == null) {
33 Class<? extends HttpUrlRequestFactory> factoryClass =
34 HttpUrlRequestFactory.class.getClassLoader().
35 loadClass(CHROMIUM_URL_REQUEST_FACTORY).
36 asSubclass(HttpUrlRequestFactory.class);
37 Constructor<? extends HttpUrlRequestFactory> constructor =
38 factoryClass.getConstructor(Context.class);
39 HttpUrlRequestFactory chromiumFactory =
40 constructor.newInstance(context);
41 if (chromiumFactory.isEnabled()) {
42 sFactory = chromiumFactory;
44 } catch (ClassNotFoundException e) {
46 } catch (Exception e) {
47 throw new IllegalStateException(
48 "Cannot instantiate: " +
49 CHROMIUM_URL_REQUEST_FACTORY,
52 if (sFactory == null) {
53 // Default to HttpUrlConnection-based networking.
54 sFactory = new HttpUrlConnectionUrlRequestFactory(context);
56 Log.i(TAG, "Using network stack: " + sFactory.getName());
63 * Creates a new request intended for full-response buffering.
65 public static HttpUrlRequest newRequest(Context context, String url,
66 int requestPriority, Map<String, String> headers,
67 HttpUrlRequestListener listener) {
68 return getFactory(context).createRequest(url, requestPriority, headers,
73 * Creates a new request intended for streaming the response.
75 public static HttpUrlRequest newRequest(Context context, String url,
76 int requestPriority, Map<String, String> headers,
77 WritableByteChannel channel, HttpUrlRequestListener listener) {
78 return getFactory(context).createRequest(url, requestPriority, headers,
83 * Returns true if the factory is enabled.
85 protected abstract boolean isEnabled();
88 * Returns a human-readable name of the factory.
90 protected abstract String getName();
93 * Creates a new request intended for full-response buffering.
95 protected abstract HttpUrlRequest createRequest(String url,
96 int requestPriority, Map<String, String> headers,
97 HttpUrlRequestListener listener);
100 * Creates a new request intended for streaming.
102 protected abstract HttpUrlRequest createRequest(String url,
103 int requestPriority, Map<String, String> headers,
104 WritableByteChannel channel, HttpUrlRequestListener listener);