Honor NetworkSecurityPolicy regarding cleartext traffic.

This makes okhttp's Android URLStreamHandler instances honor the
process-wide policy about cleartext network traffic. If cleartext
network traffic is not permitted, then attempts to open okhttp-backed
URLConnections will throw an IOException.

Cleartext HTTP attempts violating the policy will now result in
URLConnection throwing a java.net.SocketException complaining that no
route to the host could be found because no connection specs are
available. The message or the exception type could be improved upon
for easier troubleshooting. However, this is how okhttp decided to
handle this policy for now. We could intercept connection attempts
earlier, and throw our own exception, but it's not clear how much
benefit this additional complexity will provider.

Bug: 19215516
Change-Id: I38afc86eeee8b1c237e9ae45c4ca884dc7310152
diff --git a/android/main/java/com/squareup/okhttp/HttpHandler.java b/android/main/java/com/squareup/okhttp/HttpHandler.java
index e843faf..f7518ad 100644
--- a/android/main/java/com/squareup/okhttp/HttpHandler.java
+++ b/android/main/java/com/squareup/okhttp/HttpHandler.java
@@ -17,6 +17,7 @@
 
 package com.squareup.okhttp;
 
+import libcore.net.NetworkSecurityPolicy;
 import java.io.IOException;
 import java.net.Proxy;
 import java.net.ResponseCache;
@@ -68,7 +69,15 @@
 
         // Do not permit http -> https and https -> http redirects.
         client.setFollowSslRedirects(false);
-        client.setConnectionSpecs(CLEARTEXT_ONLY);
+
+        if (NetworkSecurityPolicy.isCleartextTrafficPermitted()) {
+          // Permit cleartext traffic only (this is a handler for HTTP, not for HTTPS).
+          client.setConnectionSpecs(CLEARTEXT_ONLY);
+        } else {
+          // Cleartext HTTP denied by policy. Make okhttp deny cleartext HTTP attempts using the
+          // only mechanism it currently provides -- pretend there are no suitable routes.
+          client.setConnectionSpecs(Collections.<ConnectionSpec>emptyList());
+        }
 
         // When we do not set the Proxy explicitly OkHttp picks up a ProxySelector using
         // ProxySelector.getDefault().