From b9ab4282cf38807438acd5714bcd2f96d5240399 Mon Sep 17 00:00:00 2001 From: Lorenzo Colitti Date: Fri, 18 Jul 2014 01:34:19 +0900 Subject: [PATCH] Add a getBoundURL method that returns a network-specific URL. Change-Id: I4b57e675bb87064ab75dcc36b00fdc7a2987b86e --- core/java/android/net/Network.java | 39 ++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/core/java/android/net/Network.java b/core/java/android/net/Network.java index 9a22d78256..97238f19e1 100644 --- a/core/java/android/net/Network.java +++ b/core/java/android/net/Network.java @@ -23,11 +23,16 @@ import android.os.Parcel; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.MalformedURLException; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; +import java.net.URL; import javax.net.SocketFactory; +import com.android.okhttp.HostResolver; +import com.android.okhttp.OkHttpClient; + /** * Identifies a {@code Network}. This is supplied to applications via * {@link ConnectivityManager.NetworkCallback} in response to the active @@ -44,7 +49,11 @@ public class Network implements Parcelable { */ public final int netId; + // Objects used to perform per-network operations such as getSocketFactory + // and getBoundURL, and a lock to protect access to them. private NetworkBoundSocketFactory mNetworkBoundSocketFactory = null; + private OkHttpClient mOkHttpClient = null; + private Object mLock = new Object(); /** * @hide @@ -166,12 +175,38 @@ public class Network implements Parcelable { * {@code Network}. */ public SocketFactory getSocketFactory() { - if (mNetworkBoundSocketFactory == null) { - mNetworkBoundSocketFactory = new NetworkBoundSocketFactory(netId); + synchronized (mLock) { + if (mNetworkBoundSocketFactory == null) { + mNetworkBoundSocketFactory = new NetworkBoundSocketFactory(netId); + } } return mNetworkBoundSocketFactory; } + /** + * Returns a {@link URL} based on the given URL but bound to this {@code Network}. + * Note that if this {@code Network} ever disconnects, this factory and any URL object it + * produced in the past or future will cease to work. + * + * @return a {@link URL} bound to this {@code Network}. + */ + public URL getBoundURL(URL url) throws MalformedURLException { + synchronized (mLock) { + if (mOkHttpClient == null) { + HostResolver hostResolver = new HostResolver() { + @Override + public InetAddress[] getAllByName(String host) throws UnknownHostException { + return Network.this.getAllByName(host); + } + }; + mOkHttpClient = new OkHttpClient() + .setSocketFactory(getSocketFactory()) + .setHostResolver(hostResolver); + } + } + return new URL(url, "", mOkHttpClient.createURLStreamHandler(url.getProtocol())); + } + // implement the Parcelable interface public int describeContents() { return 0;