Code example for Proxy

Methods: address, type

0
        return new SocketPermission(connectToAddress, "connect, resolve");
    } 
 
    private String getConnectToHost() {
        return usingProxy() 
                ? ((InetSocketAddress) proxy.address()).getHostName()
                : getURL().getHost();
    } 
 
    private int getConnectToPort() { 
        int hostPort = usingProxy()
                ? ((InetSocketAddress) proxy.address()).getPort()
                : getURL().getPort();
        return hostPort < 0 ? getDefaultPort() : hostPort;
    } 
 
    @Override public final String getRequestProperty(String field) {
        if (field == null) {
            return null; 
        } 
        return rawRequestHeaders.get(field);
    } 
 
    private void initHttpEngine() throws IOException { 
        if (httpEngineFailure != null) {
            throw httpEngineFailure;
        } else if (httpEngine != null) {
            return; 
        } 
 
        connected = true;
        try { 
            if (doOutput) {
                if (method == HttpEngine.GET) {
                    // they are requesting a stream to write to. This implies a POST method 
                    method = HttpEngine.POST;
                } else if (method != HttpEngine.POST && method != HttpEngine.PUT) {
                    // If the request method is neither POST nor PUT, then you're not writing 
                    throw new ProtocolException(method + " does not support writing");
                } 
            } 
            httpEngine = newHttpEngine(method, rawRequestHeaders, null, null);
        } catch (IOException e) {
            httpEngineFailure = e;
            throw e;
        } 
    } 
 
    /** 
     * Create a new HTTP engine. This hook method is non-final so it can be 
     * overridden by HttpsURLConnectionImpl. 
     */ 
    protected HttpEngine newHttpEngine(String method, RawHeaders requestHeaders,
            HttpConnection connection, RetryableOutputStream requestBody) throws IOException {
        return new HttpEngine(this, method, requestHeaders, connection, requestBody);
    } 
 
    /** 
     * Aggressively tries to get the final HTTP response, potentially making 
     * many HTTP requests in the process in order to cope with redirects and 
     * authentication. 
     */ 
    private HttpEngine getResponse() throws IOException { 
        initHttpEngine(); 
 
        if (httpEngine.hasResponse()) {
            return httpEngine;
        } 
 
        try { 
            while (true) { 
                httpEngine.sendRequest();
                httpEngine.readResponse();
 
                Retry retry = processResponseHeaders();
                if (retry == Retry.NONE) {
                    httpEngine.automaticallyReleaseConnectionToPool();
                    break; 
                } 
 
                /* 
                 * The first request was insufficient. Prepare for another... 
                 */ 
                String retryMethod = method;
                OutputStream requestBody = httpEngine.getRequestBody();
 
                /* 
                 * Although RFC 2616 10.3.2 specifies that a HTTP_MOVED_PERM 
                 * redirect should keep the same method, Chrome, Firefox and the 
                 * RI all issue GETs when following any redirect. 
                 */ 
                int responseCode = getResponseCode();
                if (responseCode == HTTP_MULT_CHOICE || responseCode == HTTP_MOVED_PERM
                        || responseCode == HTTP_MOVED_TEMP || responseCode == HTTP_SEE_OTHER) {
                    retryMethod = HttpEngine.GET;
                    requestBody = null;
                } 
 
                if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
                    throw new HttpRetryException("Cannot retry streamed HTTP body",
                            httpEngine.getResponseCode());
                } 
 
                if (retry == Retry.DIFFERENT_CONNECTION) {
                    httpEngine.automaticallyReleaseConnectionToPool();
                } 
 
                httpEngine.release(true);
 
                httpEngine = newHttpEngine(retryMethod, rawRequestHeaders,
                        httpEngine.getConnection(), (RetryableOutputStream) requestBody);
            } 
            return httpEngine;
        } catch (IOException e) {
            httpEngineFailure = e;
            throw e;
        } 
    } 
 
    HttpEngine getHttpEngine() { 
        return httpEngine;
    } 
 
    enum Retry { 
        NONE,
        SAME_CONNECTION,
        DIFFERENT_CONNECTION
    } 
 
    /** 
     * Returns the retry action to take for the current response headers. The 
     * headers, proxy and target URL or this connection may be adjusted to 
     * prepare for a follow up request. 
     */ 
    private Retry processResponseHeaders() throws IOException { 
        switch (getResponseCode()) { 
        case HTTP_PROXY_AUTH:
            if (!usingProxy()) { 
                throw new IOException(
                        "Received HTTP_PROXY_AUTH (407) code while not using proxy"); 
            } 
            // fall-through 
        case HTTP_UNAUTHORIZED:
            boolean credentialsFound = processAuthHeader(getResponseCode(),
                    httpEngine.getResponseHeaders(), rawRequestHeaders);
            return credentialsFound ? Retry.SAME_CONNECTION : Retry.NONE;
 
        case HTTP_MULT_CHOICE:
        case HTTP_MOVED_PERM:
        case HTTP_MOVED_TEMP:
        case HTTP_SEE_OTHER:
            if (!getInstanceFollowRedirects()) {
                return Retry.NONE;
            } 
            if (++redirectionCount > HttpEngine.MAX_REDIRECTS) {
                throw new ProtocolException("Too many redirects");
            } 
            String location = getHeaderField("Location");
            if (location == null) {
                return Retry.NONE;
            } 
            URL previousUrl = url;
            url = new URL(previousUrl, location);
            if (!previousUrl.getProtocol().equals(url.getProtocol())) {
                return Retry.NONE; // the scheme changed; don't retry.
            } 
            if (previousUrl.getHost().equals(url.getHost())
                    && previousUrl.getEffectivePort() == url.getEffectivePort()) {
                return Retry.SAME_CONNECTION;
            } else { 
                return Retry.DIFFERENT_CONNECTION;
            } 
 
        default: 
            return Retry.NONE;
        } 
    } 
 
    /** 
     * React to a failed authorization response by looking up new credentials. 
     * 
     * @return true if credentials have been added to successorRequestHeaders 
     *     and another request should be attempted. 
     */ 
    final boolean processAuthHeader(int responseCode, ResponseHeaders response,
            RawHeaders successorRequestHeaders) throws IOException {
        if (responseCode != HTTP_PROXY_AUTH && responseCode != HTTP_UNAUTHORIZED) {
            throw new IllegalArgumentException();
        } 
 
        // keep asking for username/password until authorized 
        String challenge = responseCode == HTTP_PROXY_AUTH
                ? response.getProxyAuthenticate()
                : response.getWwwAuthenticate();
        if (challenge == null) {
            throw new IOException("Received authentication challenge is null");
        } 
        String credentials = getAuthorizationCredentials(challenge);
        if (credentials == null) {
            return false; // could not find credentials, end request cycle 
        } 
 
        // add authorization credentials, bypassing the already-connected check 
        String fieldName = responseCode == HTTP_PROXY_AUTH
                ? "Proxy-Authorization" 
                : "Authorization"; 
        successorRequestHeaders.set(fieldName, credentials);
        return true; 
    } 
 
    /** 
     * Returns the authorization credentials on the base of provided challenge. 
     */ 
    private String getAuthorizationCredentials(String challenge) throws IOException {
        int idx = challenge.indexOf(" ");
        if (idx == -1) {
            return null; 
        } 
        String scheme = challenge.substring(0, idx);
        int realm = challenge.indexOf("realm=\"") + 7;
        String prompt = null;
        if (realm != -1) {
            int end = challenge.indexOf('"', realm);
            if (end != -1) {
                prompt = challenge.substring(realm, end);
            } 
        } 
        // use the global authenticator to get the password 
        PasswordAuthentication pa = Authenticator.requestPasswordAuthentication(
                getConnectToInetAddress(), getConnectToPort(), url.getProtocol(), prompt, scheme);
        if (pa == null) {
            return null; 
        } 
        // base64 encode the username and password 
        String usernameAndPassword = pa.getUserName() + ":" + new String(pa.getPassword());
        byte[] bytes = usernameAndPassword.getBytes(Charsets.ISO_8859_1);
        String encoded = Base64.encode(bytes);
        return scheme + " " + encoded;
    } 
 
    private InetAddress getConnectToInetAddress() throws IOException {
        return usingProxy() 
                ? ((InetSocketAddress) proxy.address()).getAddress()
                : InetAddress.getByName(getURL().getHost());
    } 
 
    final int getDefaultPort() { 
        return defaultPort;
    } 
 
    /** @see HttpURLConnection#setFixedLengthStreamingMode(int) */ 
    final int getFixedContentLength() { 
        return fixedContentLength;
    } 
 
    /** @see HttpURLConnection#setChunkedStreamingMode(int) */ 
    final int getChunkLength() { 
        return chunkLength;
    } 
 
    final Proxy getProxy() {
        return proxy;
    } 
 
    final void setProxy(Proxy proxy) {
        this.proxy = proxy;
    } 
 
    @Override public final boolean usingProxy() { 
        return (proxy != null && proxy.type() != Proxy.Type.DIRECT);
    } 
 
    @Override public String getResponseMessage() throws IOException {
        return getResponse().getResponseHeaders().getHeaders().getResponseMessage(); 
    }