Skip to content

Commit

Permalink
Use HttpUrl internally.
Browse files Browse the repository at this point in the history
  • Loading branch information
squarejesse committed Aug 3, 2015
1 parent a52c510 commit 4c90a2e
Show file tree
Hide file tree
Showing 19 changed files with 109 additions and 161 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import com.squareup.okhttp.internal.SslContextBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.SSLContext;
Expand Down Expand Up @@ -51,13 +50,13 @@ class ApacheHttpClient extends SynchronousHttpClient {
}

@Override public Runnable request(HttpUrl url) {
return new ApacheHttpClientRequest(url.url());
return new ApacheHttpClientRequest(url);
}

class ApacheHttpClientRequest implements Runnable {
private final URL url;
private final HttpUrl url;

public ApacheHttpClientRequest(URL url) {
public ApacheHttpClientRequest(HttpUrl url) {
this.url = url;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ static Response createOkResponseForCacheGet(Request request, CacheResponse javaR
}

Request cacheRequest = new Request.Builder()
.url(request.url())
.url(request.httpUrl())
.method(request.method(), null)
.headers(varyHeaders)
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,25 @@
package com.squareup.okhttp.android;

import com.squareup.okhttp.AndroidInternal;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.OkUrlFactory;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.io.InputStream;
import java.net.CacheRequest;
import java.net.CacheResponse;
import java.net.ResponseCache;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
Expand Down Expand Up @@ -145,7 +143,7 @@ public CacheRequest put(URI uri, URLConnection connection) {
.addHeader("Cache-Control: max-age=60")
.setBody("A"));

URLConnection c1 = openUrl(server.getUrl("/"));
URLConnection c1 = openUrl(server.url("/"));

InputStream inputStream = c1.getInputStream();
assertEquals('A', inputStream.read());
Expand All @@ -154,21 +152,21 @@ public CacheRequest put(URI uri, URLConnection connection) {
assertEquals(1, cache.getNetworkCount());
assertEquals(0, cache.getHitCount());

URLConnection c2 = openUrl(server.getUrl("/"));
URLConnection c2 = openUrl(server.url("/"));
assertEquals('A', c2.getInputStream().read());

URLConnection c3 = openUrl(server.getUrl("/"));
URLConnection c3 = openUrl(server.url("/"));
assertEquals('A', c3.getInputStream().read());
assertEquals(3, cache.getRequestCount());
assertEquals(1, cache.getNetworkCount());
assertEquals(2, cache.getHitCount());
}

// This mimics the Android HttpHandler, which is found in the com.squareup.okhttp package.
private URLConnection openUrl(URL url) {
private URLConnection openUrl(HttpUrl url) {
ResponseCache responseCache = ResponseCache.getDefault();
AndroidInternal.setResponseCache(client, responseCache);
return client.open(url);
return client.open(url.url());
}

private void initializeCache(HttpResponseCache cache) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public class JavaApiConverterTest {

Response response = JavaApiConverter.createOkResponseForCacheGet(request, cacheResponse);
Request cacheRequest = response.request();
assertEquals(request.url(), cacheRequest.url());
assertEquals(request.httpUrl(), cacheRequest.httpUrl());
assertEquals(request.method(), cacheRequest.method());
assertEquals(0, request.headers().size());

Expand Down Expand Up @@ -198,7 +198,7 @@ public class JavaApiConverterTest {

Response response = JavaApiConverter.createOkResponseForCacheGet(request, cacheResponse);
Request cacheRequest = response.request();
assertEquals(request.url(), cacheRequest.url());
assertEquals(request.httpUrl(), cacheRequest.httpUrl());
assertEquals(request.method(), cacheRequest.method());
assertEquals(0, request.headers().size());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
Expand Down Expand Up @@ -139,7 +138,7 @@ public final class InterceptorTest {
String sameHost = address.getUriHost();
int differentPort = address.getUriPort() + 1;
return chain.proceed(chain.request().newBuilder()
.url(new URL("http://" + sameHost + ":" + differentPort + "/"))
.url(HttpUrl.parse("http://" + sameHost + ":" + differentPort + "/"))
.build());
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import com.squareup.okhttp.Cache;
import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.OkUrlFactory;
import com.squareup.okhttp.Protocol;
Expand All @@ -34,7 +35,6 @@
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
Expand Down Expand Up @@ -380,13 +380,13 @@ protected HttpOverSpdyTest(Protocol protocol){
server.enqueue(new MockResponse()
.setBody("B"));

URL url = server.getUrl("/");
assertContent("A", client.open(url), Integer.MAX_VALUE);
HttpUrl url = server.url("/");
assertContent("A", client.open(url.url()), Integer.MAX_VALUE);
Map<String, List<String>> requestHeaders = Collections.emptyMap();
assertEquals(Collections.singletonMap("Cookie", Arrays.asList("c=oreo")),
cookieManager.get(url.toURI(), requestHeaders));
cookieManager.get(url.uri(), requestHeaders));

assertContent("B", client.open(url), Integer.MAX_VALUE);
assertContent("B", client.open(url.url()), Integer.MAX_VALUE);
RecordedRequest requestA = server.takeRequest();
assertNull(requestA.getHeader("Cookie"));
RecordedRequest requestB = server.takeRequest();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.squareup.okhttp.Connection;
import com.squareup.okhttp.Handshake;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.Request;
Expand All @@ -28,14 +29,13 @@
import com.squareup.okhttp.Route;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.Platform;
import com.squareup.okhttp.internal.http.RouteException;
import com.squareup.okhttp.internal.Util;
import com.squareup.okhttp.internal.http.HttpDate;
import com.squareup.okhttp.internal.http.HttpEngine;
import com.squareup.okhttp.internal.http.HttpMethod;
import com.squareup.okhttp.internal.http.OkHeaders;
import com.squareup.okhttp.internal.http.RequestException;
import com.squareup.okhttp.internal.http.RetryableSink;
import com.squareup.okhttp.internal.http.RouteException;
import com.squareup.okhttp.internal.http.StatusLine;
import java.io.FileNotFoundException;
import java.io.IOException;
Expand Down Expand Up @@ -255,8 +255,11 @@ private static String responseSourceHeader(Response response) {
}

@Override public final Permission getPermission() throws IOException {
String hostName = getURL().getHost();
int hostPort = Util.getEffectivePort(getURL());
URL url = getURL();
String hostName = url.getHost();
int hostPort = url.getPort() != -1
? url.getPort()
: HttpUrl.defaultPort(url.getProtocol());
if (usingProxy()) {
InetSocketAddress proxyAddress = (InetSocketAddress) client.getProxy().address();
hostName = proxyAddress.getHostName();
Expand Down Expand Up @@ -413,7 +416,7 @@ private HttpEngine getResponse() throws IOException {
throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
}

if (!httpEngine.sameConnection(followUp.url())) {
if (!httpEngine.sameConnection(followUp.httpUrl())) {
httpEngine.releaseConnection();
}

Expand Down
16 changes: 5 additions & 11 deletions okhttp/src/main/java/com/squareup/okhttp/Call.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,11 @@
package com.squareup.okhttp;

import com.squareup.okhttp.internal.NamedRunnable;
import com.squareup.okhttp.internal.http.RouteException;
import com.squareup.okhttp.internal.http.HttpEngine;
import com.squareup.okhttp.internal.http.RequestException;
import com.squareup.okhttp.internal.http.RouteException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.logging.Level;

import static com.squareup.okhttp.internal.Internal.logger;
Expand Down Expand Up @@ -139,7 +137,7 @@ private AsyncCall(Callback responseCallback, boolean forWebSocket) {
}

String host() {
return originalRequest.url().getHost();
return originalRequest.httpUrl().host();
}

Request request() {
Expand Down Expand Up @@ -188,12 +186,8 @@ Call get() {
*/
private String toLoggableString() {
String string = canceled ? "canceled call" : "call";
try {
String redactedUrl = new URL(originalRequest.url(), "/...").toString();
return string + " to " + redactedUrl;
} catch (MalformedURLException e) {
return string;
}
HttpUrl redactedUrl = originalRequest.httpUrl().resolve("/...");
return string + " to " + redactedUrl;
}

private Response getResponseWithInterceptorChain(boolean forWebSocket) throws IOException {
Expand Down Expand Up @@ -310,7 +304,7 @@ Response getResponse(Request request, boolean forWebSocket) throws IOException {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}

if (!engine.sameConnection(followUp.url())) {
if (!engine.sameConnection(followUp.httpUrl())) {
engine.releaseConnection();
}

Expand Down
19 changes: 9 additions & 10 deletions okhttp/src/main/java/com/squareup/okhttp/Connection.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.io.IOException;
import java.net.Proxy;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownServiceException;
import java.security.cert.X509Certificate;
import java.util.List;
Expand All @@ -44,8 +43,6 @@
import okio.Source;

import static com.squareup.okhttp.internal.Util.closeQuietly;
import static com.squareup.okhttp.internal.Util.getDefaultPort;
import static com.squareup.okhttp.internal.Util.getEffectivePort;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PROXY_AUTH;

Expand Down Expand Up @@ -279,8 +276,8 @@ private void createTunnel(int readTimeout, int writeTimeout, Request request) th
Request tunnelRequest = createTunnelRequest(request);
HttpConnection tunnelConnection = new HttpConnection(pool, this, socket);
tunnelConnection.setTimeouts(readTimeout, writeTimeout);
URL url = tunnelRequest.url();
String requestLine = "CONNECT " + url.getHost() + ":" + getEffectivePort(url) + " HTTP/1.1";
HttpUrl url = tunnelRequest.httpUrl();
String requestLine = "CONNECT " + url.host() + ":" + url.port() + " HTTP/1.1";
while (true) {
tunnelConnection.writeRequest(tunnelRequest.headers(), requestLine);
tunnelConnection.flush();
Expand Down Expand Up @@ -327,12 +324,14 @@ private void createTunnel(int readTimeout, int writeTimeout, Request request) th
* to the proxy unencrypted.
*/
private Request createTunnelRequest(Request request) throws IOException {
String host = request.url().getHost();
int port = getEffectivePort(request.url());
String authority = (port == getDefaultPort("https")) ? host : (host + ":" + port);
HttpUrl tunnelUrl = new HttpUrl.Builder()
.scheme("https")
.host(request.httpUrl().host())
.port(request.httpUrl().port())
.build();
Request.Builder result = new Request.Builder()
.url(new URL("https", host, port, "/"))
.header("Host", authority)
.url(tunnelUrl)
.header("Host", Util.hostHeader(tunnelUrl))
.header("Proxy-Connection", "Keep-Alive"); // For HTTP/1.0 proxies like Squid.

// Copy over the User-Agent header if it exists.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package com.squareup.okhttp.internal;

import com.squareup.okhttp.ConnectionSpec;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ProtocolException;
Expand Down
28 changes: 8 additions & 20 deletions okhttp/src/main/java/com/squareup/okhttp/internal/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,14 @@

package com.squareup.okhttp.internal;

import com.squareup.okhttp.HttpUrl;
import java.io.Closeable;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
Expand All @@ -51,24 +50,6 @@ public final class Util {
private Util() {
}

public static int getEffectivePort(URI uri) {
return getEffectivePort(uri.getScheme(), uri.getPort());
}

public static int getEffectivePort(URL url) {
return getEffectivePort(url.getProtocol(), url.getPort());
}

private static int getEffectivePort(String scheme, int specifiedPort) {
return specifiedPort != -1 ? specifiedPort : getDefaultPort(scheme);
}

public static int getDefaultPort(String protocol) {
if ("http".equals(protocol)) return 80;
if ("https".equals(protocol)) return 443;
return -1;
}

public static void checkOffsetAndCount(long arrayLength, long offset, long count) {
if ((offset | count) < 0 || offset > arrayLength || arrayLength - offset < count) {
throw new ArrayIndexOutOfBoundsException();
Expand Down Expand Up @@ -272,4 +253,11 @@ private static <T> List<T> intersect(T[] first, T[] second) {
}
return result;
}

public static String hostHeader(HttpUrl url) {
// TODO: square braces for IPv6 ?
return url.port() != HttpUrl.defaultPort(url.scheme())
? url.host() + ":" + url.port()
: url.host();
}
}
Loading

0 comments on commit 4c90a2e

Please sign in to comment.