Java Code Examples for java.net.HttpRetryException

The following examples show how to use java.net.HttpRetryException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: AsyncOkHttpClient   Source File: ByteAsyncHttpResponse.java    License: Apache License 2.0 6 votes vote down vote up
@Override
void sendResponseMessage(HttpURLConnection connection) {
	InputStream response = null;
	byte[] responseBody = null;
	try {
		int statusCode = connection.getResponseCode();
		if(statusCode >= 300) {
			response = connection.getErrorStream();
			if(response != null) responseBody = Util.inputStreamToByteArray(response);
			sendFailMessage(new HttpRetryException(connection.getResponseMessage(), statusCode), 
					responseBody);		
		} else {
			response = connection.getInputStream();
			if(response != null) responseBody = Util.inputStreamToByteArray(response);
			sendSuccessMessage(statusCode, responseBody);
		}
	} catch(IOException e) {
		sendFailMessage(e, (byte[])null);
	} finally {
		if(response != null) Util.closeQuietly(response);
	}
}
 
Example 2
Source Project: AsyncOkHttpClient   Source File: AsyncHttpResponse.java    License: Apache License 2.0 6 votes vote down vote up
/**
    * Perform the connection with the given client
    * and return the response to the relative callback
    * @param connection the connection to execute and collect the informations
    */
void sendResponseMessage(HttpURLConnection connection) {
	String responseBody = null;
	InputStream response = null;
	try {
		int responseCode = connection.getResponseCode();
		if(responseCode >= 300) {
			response = connection.getErrorStream();
			if(response != null) responseBody = Util.inputStreamToString(response);
               sendFailMessage(new HttpRetryException(connection.getResponseMessage(),
                       responseCode), responseBody);
		} else {
			response = connection.getInputStream();
			if(response != null) responseBody = Util.inputStreamToString(response);
			sendSuccessMessage(responseCode, responseBody);
		}
	} catch(IOException e) {
		sendFailMessage(e, (String)null);
	} finally {
		if(response != null) Util.closeQuietly(response);
	}
}
 
Example 3
Source Project: jdk8u60   Source File: HttpURLConnection.java    License: GNU General Public License v2.0 4 votes vote down vote up
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
        // need to remember this in case NTLM proxy authentication gets
        // used. We can't use transparent authentication when user
        // doesn't know about proxy.
        useProxyResponseCode = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = url.getHost();
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 4
@Override
public void rewind(UploadDataSink uploadDataSink) {
    uploadDataSink.onRewindError(
            new HttpRetryException("Cannot retry streamed Http body", -1));
}
 
Example 5
@Override
public void rewind(UploadDataSink uploadDataSink) {
    uploadDataSink.onRewindError(
            new HttpRetryException("Cannot retry streamed Http body", -1));
}
 
Example 6
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
        // need to remember this in case NTLM proxy authentication gets
        // used. We can't use transparent authentication when user
        // doesn't know about proxy.
        useProxyResponseCode = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = url.getHost();
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 7
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
        // need to remember this in case NTLM proxy authentication gets
        // used. We can't use transparent authentication when user
        // doesn't know about proxy.
        useProxyResponseCode = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = stripIPv6ZoneId(url.getHost());
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 8
Source Project: jdk8u-jdk   Source File: HttpURLConnection.java    License: GNU General Public License v2.0 4 votes vote down vote up
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
        // need to remember this in case NTLM proxy authentication gets
        // used. We can't use transparent authentication when user
        // doesn't know about proxy.
        useProxyResponseCode = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = url.getHost();
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 9
Source Project: hottub   Source File: HttpURLConnection.java    License: GNU General Public License v2.0 4 votes vote down vote up
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
        // need to remember this in case NTLM proxy authentication gets
        // used. We can't use transparent authentication when user
        // doesn't know about proxy.
        useProxyResponseCode = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = url.getHost();
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 10
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = url.getHost();
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 11
Source Project: openjdk-8   Source File: HttpURLConnection.java    License: GNU General Public License v2.0 4 votes vote down vote up
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = url.getHost();
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 12
Source Project: L.TileLayer.Cordova   Source File: HttpURLConnectionImpl.java    License: MIT License 4 votes vote down vote up
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
Example 13
Source Project: IoTgo_Android_App   Source File: HttpURLConnectionImpl.java    License: MIT License 4 votes vote down vote up
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
Example 14
Source Project: jdk8u-jdk   Source File: HttpURLConnection.java    License: GNU General Public License v2.0 4 votes vote down vote up
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
        // need to remember this in case NTLM proxy authentication gets
        // used. We can't use transparent authentication when user
        // doesn't know about proxy.
        useProxyResponseCode = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = url.getHost();
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 15
Source Project: android-discourse   Source File: HttpURLConnectionImpl.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 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;
    }

    while (true) {
        if (!execute(true)) {
            continue;
        }

        Retry retry = processResponseHeaders();
        if (retry == Retry.NONE) {
            httpEngine.automaticallyReleaseConnectionToPool();
            return httpEngine;
        }

        // 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 = "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(false);

        httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(), (RetryableOutputStream) requestBody);

        if (requestBody == null) {
            // Drop the Content-Length header when redirected from POST to GET.
            httpEngine.getRequestHeaders().removeContentLength();
        }
    }
}
 
Example 16
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
        // need to remember this in case NTLM proxy authentication gets
        // used. We can't use transparent authentication when user
        // doesn't know about proxy.
        useProxyResponseCode = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = url.getHost();
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 17
Source Project: bluemix-parking-meter   Source File: HttpURLConnectionImpl.java    License: MIT License 4 votes vote down vote up
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
Example 18
Source Project: j2objc   Source File: URLConnectionTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
     * Test that request body chunking works. This test has been relaxed from treating
     * the {@link java.net.HttpURLConnection#setChunkedStreamingMode(int)}
     * chunk length as being fixed because OkHttp no longer guarantees
     * the fixed chunk size. Instead, we check that chunking takes place
     * and we force the chunk size with flushes.
     */
//    public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
//        server.enqueue(new MockResponse());
//        server.play();
//
//        HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
//        // Later releases of Android ignore the value for chunkLength if it is > 0 and default to
//        // a fixed chunkLength. During the change-over period while the chunkLength indicates the
//        // chunk buffer size (inc. header) the chunkLength has to be >= 8. This enables the flush()
//        // to dictate the size of the chunks.
//        urlConnection.setChunkedStreamingMode(50 /* chunkLength */);
//        urlConnection.setDoOutput(true);
//        OutputStream outputStream = urlConnection.getOutputStream();
//        String outputString = "ABCDEFGH";
//        byte[] outputBytes = outputString.getBytes("US-ASCII");
//        int targetChunkSize = 3;
//        for (int i = 0; i < outputBytes.length; i += targetChunkSize) {
//            int count = i + targetChunkSize < outputBytes.length ? 3 : outputBytes.length - i;
//            outputStream.write(outputBytes, i, count);
//            outputStream.flush();
//        }
//        assertEquals(200, urlConnection.getResponseCode());
//
//        RecordedRequest request = server.takeRequest();
//        assertEquals(outputString, new String(request.getBody(), "US-ASCII"));
//        assertEquals(Arrays.asList(3, 3, 2), request.getChunkSizes());
//    }

// TODO(tball): b/28067294
//    public void testAuthenticateWithFixedLengthStreaming() throws Exception {
//        testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH);
//    }

// TODO(tball): b/28067294
//    public void testAuthenticateWithChunkedStreaming() throws Exception {
//        testAuthenticateWithStreamingPost(StreamingMode.CHUNKED);
//    }

    private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
        MockResponse pleaseAuthenticate = new MockResponse()
                .setResponseCode(401)
                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
                .setBody("Please authenticate.");
        server.enqueue(pleaseAuthenticate);
        server.play();

        Authenticator.setDefault(new SimpleAuthenticator());
        HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
        connection.setDoOutput(true);
        byte[] requestBody = { 'A', 'B', 'C', 'D' };
        if (streamingMode == StreamingMode.FIXED_LENGTH) {
            connection.setFixedLengthStreamingMode(requestBody.length);
        } else if (streamingMode == StreamingMode.CHUNKED) {
            connection.setChunkedStreamingMode(0);
        }
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(requestBody);
        outputStream.close();
        try {
            connection.getInputStream();
            fail();
        } catch (HttpRetryException expected) {
        }

        // no authorization header for the request...
        RecordedRequest request = server.takeRequest();
        assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*");
        assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody()));
    }
 
Example 19
Source Project: reader   Source File: HttpURLConnectionImpl.java    License: MIT License 4 votes vote down vote up
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
Example 20
Source Project: reader   Source File: HttpURLConnectionImpl.java    License: MIT License 4 votes vote down vote up
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
Example 21
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
Example 22
Source Project: catch-exception   Source File: CatchThrowableTest.java    License: Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    // set any exception so that we have clear state before the test
    ThrowableHolder.set(new HttpRetryException("detail", 0));
}
 
Example 23
Source Project: catch-exception   Source File: CatchExceptionTest.java    License: Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    // set any exception so that we have clear state before the test
    ExceptionHolder.set(new HttpRetryException("detail", 0));
}
 
Example 24
Source Project: phonegapbootcampsite   Source File: HttpURLConnectionImpl.java    License: MIT License 4 votes vote down vote up
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
Example 25
Source Project: cxf   Source File: HTTPConduit.java    License: Apache License 2.0 4 votes vote down vote up
protected void handleHttpRetryException(HttpRetryException e) throws IOException {
    String msg = "HTTP response '" + e.responseCode() + ": "
        + getResponseMessage() + "' invoking " + url;
    switch (e.responseCode()) {
    case HttpURLConnection.HTTP_MOVED_PERM: // 301
    case HttpURLConnection.HTTP_MOVED_TEMP: // 302
    case HttpURLConnection.HTTP_SEE_OTHER:  // 303
    case 307:
        msg += " that returned location header '" + e.getLocation() + "'";
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED: // 401
        if (authorizationPolicy == null || authorizationPolicy.getUserName() == null) {
            msg += " with NO authorization username configured in conduit " + getConduitName();
        } else {
            msg += " with authorization username '" + authorizationPolicy.getUserName() + "'";
        }
        break;
    case HttpURLConnection.HTTP_PROXY_AUTH: // 407
        if (proxyAuthorizationPolicy == null || proxyAuthorizationPolicy.getUserName() == null) {
            msg += " with NO proxy authorization configured in conduit " + getConduitName();
        } else {
            msg += " with proxy authorization username '"
                + proxyAuthorizationPolicy.getUserName() + "'";
        }
        if (clientSidePolicy == null || clientSidePolicy.getProxyServer() == null) {
            if (usingProxy()) {
                msg += " using a proxy even if NONE is configured in CXF conduit "
                    + getConduitName()
                    + " (maybe one is configured by java.net.ProxySelector)";
            } else {
                msg += " but NO proxy was used by the connection (none configured in cxf "
                    + "conduit and none selected by java.net.ProxySelector)";
            }
        } else {
            msg += " using " + clientSidePolicy.getProxyServerType() + " proxy "
                + clientSidePolicy.getProxyServer() + ":"
                + clientSidePolicy.getProxyServerPort();
        }
        break;
    default:
        // No other type of HttpRetryException should be thrown
        break;
    }
    throw new IOException(msg, e);
}
 
Example 26
Source Project: CordovaYoutubeVideoPlayer   Source File: HttpURLConnectionImpl.java    License: MIT License 4 votes vote down vote up
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
Example 27
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = "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(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);
  }
}
 
Example 28
Source Project: wildfly-samples   Source File: HttpURLConnectionImpl.java    License: MIT License 4 votes vote down vote up
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = httpEngine.getResponseCode();
    if (responseCode == HTTP_MULT_CHOICE
        || responseCode == HTTP_MOVED_PERM
        || responseCode == HTTP_MOVED_TEMP
        || responseCode == HTTP_SEE_OTHER) {
      retryMethod = "GET";
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

    if (retry == Retry.DIFFERENT_CONNECTION) {
      httpEngine.automaticallyReleaseConnectionToPool();
    }

    httpEngine.release(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);

    if (requestBody == null) {
      // Drop the Content-Length header when redirected from POST to GET.
      httpEngine.getRequestHeaders().removeContentLength();
    }
  }
}
 
Example 29
Source Project: apiman   Source File: HttpURLConnectionImpl.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Response response = httpEngine.getResponse();
    Request followUp = httpEngine.followUpRequest();

    if (followUp == null) {
      httpEngine.releaseConnection();
      return httpEngine;
    }

    if (++followUpCount > HttpEngine.MAX_FOLLOW_UPS) {
      throw new ProtocolException("Too many follow-up requests: " + followUpCount);
    }

    // The first request was insufficient. Prepare for another...
    url = followUp.url();
    requestHeaders = followUp.headers().newBuilder();

    // 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.
    Sink requestBody = httpEngine.getRequestBody();
    if (!followUp.method().equals(method)) {
      requestBody = null;
    }

    if (requestBody != null && !(requestBody instanceof RetryableSink)) {
      throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
    }

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

    Connection connection = httpEngine.close();
    httpEngine = newHttpEngine(followUp.method(), connection, (RetryableSink) requestBody,
        response);
  }
}
 
Example 30
/**
 * 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;
  }

  while (true) {
    if (!execute(true)) {
      continue;
    }

    Retry retry = processResponseHeaders();
    if (retry == Retry.NONE) {
      httpEngine.automaticallyReleaseConnectionToPool();
      return httpEngine;
    }

    // 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 = "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(false);

    httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
        (RetryableOutputStream) requestBody);
  }
}