Search in sources :

Example 26 with Proxy

use of java.net.Proxy in project okhttp by square.

the class MockWebServer method toProxyAddress.

public Proxy toProxyAddress() {
    before();
    InetSocketAddress address = new InetSocketAddress(inetSocketAddress.getAddress(), getPort());
    return new Proxy(Proxy.Type.HTTP, address);
}
Also used : Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress)

Example 27 with Proxy

use of java.net.Proxy in project okhttp by square.

the class CallTest method connectTimeoutsAttemptsAlternateRoute.

/**
   * Make a request with two routes. The first route will time out because it's connecting to a
   * special address that never connects. The automatic retry will succeed.
   */
@Test
public void connectTimeoutsAttemptsAlternateRoute() throws Exception {
    InetSocketAddress unreachableAddress = new InetSocketAddress("10.255.255.1", 8080);
    RecordingProxySelector proxySelector = new RecordingProxySelector();
    proxySelector.proxies.add(new Proxy(Proxy.Type.HTTP, unreachableAddress));
    proxySelector.proxies.add(server.toProxyAddress());
    server.enqueue(new MockResponse().setBody("success!"));
    client = client.newBuilder().proxySelector(proxySelector).readTimeout(100, TimeUnit.MILLISECONDS).connectTimeout(100, TimeUnit.MILLISECONDS).build();
    Request request = new Request.Builder().url("http://android.com/").build();
    executeSynchronously(request).assertCode(200).assertBody("success!");
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress) RecordingProxySelector(okhttp3.internal.http.RecordingProxySelector) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 28 with Proxy

use of java.net.Proxy in project okhttp by square.

the class CallTest method readTimeoutFails.

/**
   * Make a request with two routes. The first route will fail because the null server connects but
   * never responds. The manual retry will succeed.
   */
@Test
public void readTimeoutFails() throws Exception {
    InetSocketAddress nullServerAddress = startNullServer();
    RecordingProxySelector proxySelector = new RecordingProxySelector();
    proxySelector.proxies.add(new Proxy(Proxy.Type.HTTP, nullServerAddress));
    proxySelector.proxies.add(server.toProxyAddress());
    server.enqueue(new MockResponse().setBody("success!"));
    client = client.newBuilder().proxySelector(proxySelector).readTimeout(100, TimeUnit.MILLISECONDS).build();
    Request request = new Request.Builder().url("http://android.com/").build();
    executeSynchronously(request).assertFailure(SocketTimeoutException.class);
    executeSynchronously(request).assertCode(200).assertBody("success!");
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress) RecordingProxySelector(okhttp3.internal.http.RecordingProxySelector) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 29 with Proxy

use of java.net.Proxy in project commons by twitter.

the class UrlResolverUtil method getEffectiveUrl.

/**
   * Returns the URL that {@code url} lands on, which will be the result of a 3xx redirect,
   * or {@code url} if the url does not redirect using an HTTP 3xx response code.  If there is a
   * non-2xx or 3xx HTTP response code null is returned.
   *
   * @param url The URL to follow.
   * @return The redirected URL, or {@code url} if {@code url} returns a 2XX response, otherwise
   *         null
   * @throws java.io.IOException If an error occurs while trying to follow the url.
   */
String getEffectiveUrl(String url, @Nullable ProxyConfig proxyConfig) throws IOException {
    Preconditions.checkNotNull(url);
    // Don't follow https.
    if (url.startsWith("https://")) {
        url = url.replace("https://", "http://");
    } else if (!url.startsWith("http://")) {
        url = "http://" + url;
    }
    URL urlObj = new URL(url);
    HttpURLConnection con;
    if (proxyConfig != null) {
        Proxy proxy = new Proxy(Type.HTTP, proxyConfig.getProxyAddress());
        con = (HttpURLConnection) urlObj.openConnection(proxy);
        ProxyAuthorizer.adapt(proxyConfig).authorize(con);
    } else {
        con = (HttpURLConnection) urlObj.openConnection();
    }
    try {
        // TODO(John Sirois): several commonly tweeted hosts 406 or 400 on HEADs and only work with GETs
        // fix the call chain to be able to specify retry-with-GET
        con.setRequestMethod("HEAD");
        con.setUseCaches(true);
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.setInstanceFollowRedirects(false);
        // I hate to have to do this, but some URL shorteners don't respond otherwise.
        con.setRequestProperty("User-Agent", urlToUserAgent.apply(urlObj));
        try {
            con.connect();
        } catch (StringIndexOutOfBoundsException e) {
            LOG.info("Got StringIndexOutOfBoundsException when fetching headers for " + url);
            return null;
        }
        int responseCode = con.getResponseCode();
        switch(responseCode / 100) {
            case 2:
                return url;
            case 3:
                String location = con.getHeaderField("Location");
                if (location == null) {
                    if (responseCode != 304) /* not modified */
                    {
                        LOG.info(String.format("[%d] Location header was null for URL: %s", responseCode, url));
                    }
                    return url;
                }
                // is relative, so we need to check.
                try {
                    String domain = UrlHelper.getDomainChecked(location);
                    if (domain == null || domain.isEmpty()) {
                        // This is a relative URI.
                        location = "http://" + UrlHelper.getDomain(url) + location;
                    }
                } catch (URISyntaxException e) {
                    LOG.info("location contained an invalid URI: " + location);
                }
                return location;
            default:
                LOG.info("Failed to resolve url: " + url + " with: " + responseCode + " -> " + con.getResponseMessage());
                return null;
        }
    } finally {
        con.disconnect();
    }
}
Also used : Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL)

Example 30 with Proxy

use of java.net.Proxy in project bazel by bazelbuild.

the class ProxyHelperTest method testNoProxyAuth.

@Test
public void testNoProxyAuth() throws Exception {
    Proxy proxy = ProxyHelper.createProxy("http://127.0.0.1:3128/");
    assertEquals(Proxy.Type.HTTP, proxy.type());
    assertThat(proxy.toString()).endsWith(":3128");
    assertEquals(System.getProperty("http.proxyHost"), "127.0.0.1");
    assertEquals(System.getProperty("http.proxyPort"), "3128");
}
Also used : Proxy(java.net.Proxy) Test(org.junit.Test)

Aggregations

Proxy (java.net.Proxy)132 InetSocketAddress (java.net.InetSocketAddress)71 URL (java.net.URL)44 IOException (java.io.IOException)35 Test (org.junit.Test)22 URI (java.net.URI)21 ProxySelector (java.net.ProxySelector)20 HttpURLConnection (java.net.HttpURLConnection)19 SocketAddress (java.net.SocketAddress)19 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)13 URISyntaxException (java.net.URISyntaxException)11 ServerSocket (java.net.ServerSocket)10 Socket (java.net.Socket)9 PasswordAuthentication (java.net.PasswordAuthentication)8 InterruptedIOException (java.io.InterruptedIOException)6 URLConnection (java.net.URLConnection)6 SSLServerSocket (javax.net.ssl.SSLServerSocket)6 List (java.util.List)5 SSLSocket (javax.net.ssl.SSLSocket)5 OkHttpClient (okhttp3.OkHttpClient)5