java.net.HttpRetryException Java Examples

The following examples show how to use java.net.HttpRetryException. 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 check out the related API usage on the sidebar.
Example #1
Source File: AsyncHttpResponse.java    From AsyncOkHttpClient with 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 #2
Source File: ByteAsyncHttpResponse.java    From AsyncOkHttpClient with 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 #3
Source File: URLConnectionTest.java    From j2objc with 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 #4
Source File: HttpURLConnectionImpl.java    From crosswalk-cordova-android with 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 = 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 #5
Source File: HttpURLConnectionImpl.java    From phonegap-plugin-loading-spinner with 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);
  }
}
 
Example #6
Source File: HttpURLConnectionImpl.java    From apiman with 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 #7
Source File: HttpURLConnectionImpl.java    From wildfly-samples with 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 #8
Source File: HttpURLConnectionImpl.java    From cordova-android-chromeview with 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);
  }
}
 
Example #9
Source File: HttpURLConnectionImpl.java    From CordovaYoutubeVideoPlayer with 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 #10
Source File: HTTPConduit.java    From cxf with 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 #11
Source File: HttpURLConnectionImpl.java    From phonegapbootcampsite with 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 #12
Source File: CatchExceptionTest.java    From catch-exception with 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 #13
Source File: CatchThrowableTest.java    From catch-exception with 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 #14
Source File: HttpURLConnectionImpl.java    From cordova-amazon-fireos with 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 = 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 #15
Source File: HttpURLConnectionImpl.java    From reader with 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 #16
Source File: HttpURLConnectionImpl.java    From reader with 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 #17
Source File: HttpURLConnection.java    From jdk8u60 with 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 #18
Source File: HttpURLConnectionImpl.java    From bluemix-parking-meter with 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 #19
Source File: HttpURLConnection.java    From jdk8u-dev-jdk with 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 #20
Source File: HttpURLConnectionImpl.java    From android-discourse with 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 #21
Source File: HttpURLConnection.java    From jdk8u-jdk with 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 #22
Source File: HttpURLConnectionImpl.java    From IoTgo_Android_App with 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 #23
Source File: HttpURLConnectionImpl.java    From L.TileLayer.Cordova with 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 #24
Source File: HttpURLConnection.java    From openjdk-8 with 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 #25
Source File: HttpURLConnection.java    From openjdk-8-source with 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 #26
Source File: HttpURLConnection.java    From hottub with 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 #27
Source File: HttpURLConnection.java    From jdk8u-jdk with 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 #28
Source File: HttpURLConnection.java    From openjdk-jdk9 with 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 = stripIPv6ZoneId(url.getHost());
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example #29
Source File: HttpURLConnection.java    From openjdk-jdk8u-backup with 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 #30
Source File: CronetChunkedOutputStream.java    From cronet with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void rewind(UploadDataSink uploadDataSink) {
    uploadDataSink.onRewindError(
            new HttpRetryException("Cannot retry streamed Http body", -1));
}