org.apache.http.ProtocolException Java Examples

The following examples show how to use org.apache.http.ProtocolException. 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: RedirectStrategy.java    From NetDiscovery with Apache License 2.0 7 votes vote down vote up
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if ("post".equalsIgnoreCase(method)) {
        try {
            HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) request;
            httpRequestWrapper.setURI(uri);
            httpRequestWrapper.removeHeaders("Content-Length");
            return httpRequestWrapper;
        } catch (Exception e) {

            log.error("强转为HttpRequestWrapper出错");
        }
        return new HttpPost(uri);
    } else {
        return new HttpGet(uri);
    }
}
 
Example #2
Source File: RequestEntityRestStorageService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public RequestEntityRestStorageService(final S3Session session, final HttpClientBuilder configuration) {
    super(null, new PreferencesUseragentProvider().get(), null, toProperties(session.getHost(), session.getSignatureVersion()));
    this.session = session;
    this.properties = this.getJetS3tProperties();
    // Client configuration
    configuration.disableContentCompression();
    configuration.setRetryHandler(new S3HttpRequestRetryHandler(this, preferences.getInteger("http.connections.retry")));
    configuration.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
            if(response.containsHeader("x-amz-bucket-region")) {
                final String host = ((HttpUriRequest) request).getURI().getHost();
                if(!StringUtils.equals(session.getHost().getHostname(), host)) {
                    regionEndpointCache.putRegionForBucketName(
                        StringUtils.split(StringUtils.removeEnd(((HttpUriRequest) request).getURI().getHost(), session.getHost().getHostname()), ".")[0],
                        response.getFirstHeader("x-amz-bucket-region").getValue());
                }
            }
            return super.getRedirect(request, response, context);
        }
    });
    this.setHttpClient(configuration.build());
}
 
Example #3
Source File: SimpleRedirectStrategy.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    Args.notNull(request, "HTTP request");
    Args.notNull(response, "HTTP response");

    final int statusCode = response.getStatusLine().getStatusCode();
    final String method = request.getRequestLine().getMethod();
    final Header locationHeader = response.getFirstHeader("location");
    switch (statusCode) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
        return isRedirectable(method) && locationHeader != null;
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
    case 308: // Ensure that HTTP 308 is redirected as well
        return isRedirectable(method);
    case HttpStatus.SC_SEE_OTHER:
        return true;
    default:
        return false;
    } // end of switch
}
 
Example #4
Source File: FragmentRedirectStrategy.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * @see DefaultRedirectStrategy#getRedirect(HttpRequest, HttpResponse, HttpContext)
 */
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
        throws ProtocolException {

    // Code from DefaultRedirectStrategy
    // To ensure usage of the local getLocationURI implementation.

    final URI uri = getLocationURI(request, response, context);
    final String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        return new HttpGet(uri);
    } else {
        final int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            return RequestBuilder.copy(request).setUri(uri).build();
        } else {
            return new HttpGet(uri);
        }
    }
}
 
Example #5
Source File: FragmentRedirectStrategy.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * For local redirects, converts to relative urls.
 * 
 * @param request
 *            must be an {@link OutgoingRequest}.
 */
@Override
public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    URI uri = this.redirectStrategy.getLocationURI(request, response, context);

    String resultingPageUrl = uri.toString();

    DriverRequest driverRequest = ((OutgoingRequest) request).getOriginalRequest();

    // Remove context if present
    if (StringUtils.startsWith(resultingPageUrl, driverRequest.getVisibleBaseUrl())) {
        resultingPageUrl =
                "/"
                        + StringUtils.stripStart(
                                StringUtils.replace(resultingPageUrl, driverRequest.getVisibleBaseUrl(), ""), "/");
    }
    resultingPageUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false);

    return UriUtils.createURI(ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false));
}
 
Example #6
Source File: MartiDiceRoller.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
@Override
public HttpUriRequest getRedirect(
    final HttpRequest request, final HttpResponse response, final HttpContext context)
    throws ProtocolException {
  final URI uri = getLocationURI(request, response, context);
  final String method = request.getRequestLine().getMethod();
  if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
    return new HttpHead(uri);
  } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
    return new HttpGet(uri);
  } else {
    final int status = response.getStatusLine().getStatusCode();
    if (status == HttpStatus.SC_TEMPORARY_REDIRECT
        || status == HttpStatus.SC_MOVED_PERMANENTLY
        || status == HttpStatus.SC_MOVED_TEMPORARILY) {
      return RequestBuilder.copy(request).setUri(uri).build();
    }
    return new HttpGet(uri);
  }
}
 
Example #7
Source File: LibRequestDirector.java    From YiBo with Apache License 2.0 6 votes vote down vote up
protected void rewriteRequestURI(
        final RequestWrapper request,
        final HttpRoute route) throws ProtocolException {
    try {

        URI uri = request.getURI();
        if (route.getProxyHost() != null && !route.isTunnelled()) {
            // Make sure the request URI is absolute
            if (!uri.isAbsolute()) {
                HttpHost target = route.getTargetHost();
                uri = URIUtils.rewriteURI(uri, target);
                request.setURI(uri);
            }
        } else {
            // Make sure the request URI is relative
            if (uri.isAbsolute()) {
                uri = URIUtils.rewriteURI(uri, null);
                request.setURI(uri);
            }
        }

    } catch (URISyntaxException ex) {
        throw new ProtocolException("Invalid URI: "
        		+ request.getRequestLine().getUri(), ex);
    }
}
 
Example #8
Source File: HttpUtils.java    From jitsi with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether we need to redirect.
 * @param request the initial request
 * @param response the response containing the location param for
 * redirect.
 * @param context the http context.
 * @return should we redirect.
 * @throws ProtocolException
 */
public boolean isRedirected(
        final HttpRequest request,
        final HttpResponse response,
        final HttpContext context)
    throws ProtocolException
{
    Header locationHeader = response.getFirstHeader("location");

    if(handler != null
        && locationHeader != null
        && handler.hasParams(locationHeader.getValue()))
    {
        //we will cancel this redirect and will schedule new redirect
        handler.handleRedirect(locationHeader.getValue(), parameters);
        return false;
    }

    return super.isRedirected(request, response, context);
}
 
Example #9
Source File: RequestProtocolCompliance.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * If the {@link HttpRequest} is non-compliant but 'fixable' we go ahead and
 * fix the request here. Returning the updated one.
 * 
 * @param request
 *            the request to check for compliance
 * @return the updated request
 * @throws ProtocolException
 *             when we have trouble making the request compliant
 */
public HttpRequest makeRequestCompliant(HttpRequest request)
		throws ProtocolException {
	if (requestMustNotHaveEntity(request)) {
		((HttpEntityEnclosingRequest) request).setEntity(null);
	}

	verifyRequestWithExpectContinueFlagHas100continueHeader(request);
	verifyOPTIONSRequestWithBodyHasContentType(request);
	decrementOPTIONSMaxForwardsIfGreaterThen0(request);

	if (requestVersionIsTooLow(request)) {
		return upgradeRequestTo(request, HttpVersion.HTTP_1_1);
	}

	if (requestMinorVersionIsTooHighMajorVersionsMatch(request)) {
		return downgradeRequestTo(request, HttpVersion.HTTP_1_1);
	}

	return request;
}
 
Example #10
Source File: AbstractHttpClientGenerator.java    From cetty with Apache License 2.0 6 votes vote down vote up
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if (HttpConstants.POST.equalsIgnoreCase(method)) {
        try {
            HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) request;
            httpRequestWrapper.setURI(uri);
            httpRequestWrapper.removeHeaders("Content-Length");
            return httpRequestWrapper;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HttpPost(uri);
    } else {
        return new HttpGet(uri);
    }
}
 
Example #11
Source File: CustomRedirectStrategy.java    From webmagic with Apache License 2.0 6 votes vote down vote up
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if ("post".equalsIgnoreCase(method)) {
        try {
            HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) request;
            httpRequestWrapper.setURI(uri);
            httpRequestWrapper.removeHeaders("Content-Length");
            return httpRequestWrapper;
        } catch (Exception e) {
            logger.error("强转为HttpRequestWrapper出错");
        }
        return new HttpPost(uri);
    } else {
        return new HttpGet(uri);
    }
}
 
Example #12
Source File: EntityForwardingRedirectStrategy.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Override
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException
{
    final String method = request.getRequestLine().getMethod();
    HttpUriRequest redirect = super.getRedirect(request, response, context);
    if (HttpPost.METHOD_NAME.equalsIgnoreCase(method))
    {
        HttpPost httpPostRequest = new HttpPost(redirect.getURI());
        if (request instanceof HttpEntityEnclosingRequest)
        {
            httpPostRequest.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
        }
        return httpPostRequest;
    }
    return redirect;
}
 
Example #13
Source File: EntityForwardingRedirectStrategyTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testGetRedirect() throws ProtocolException
{
    mockHeader();
    when(statusLine.getStatusCode()).thenReturn(STATUS_CODE);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    HttpEntityEnclosingRequest httpRequest = new HttpPost(URI);
    StringEntity requestStringEntity = new StringEntity("{key:value}", StandardCharsets.UTF_8);
    httpRequest.setEntity(requestStringEntity);
    HttpEntityEnclosingRequest actualRedirect = (HttpEntityEnclosingRequest) redirectStrategy
            .getRedirect(httpRequest, httpResponse, httpContext);
    assertEquals(REDIRECT_URI, actualRedirect.getRequestLine().getUri());
    assertEquals(requestStringEntity, actualRedirect.getEntity());
}
 
Example #14
Source File: RequestProtocolCompliance.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private HttpRequest upgradeRequestTo(HttpRequest request,
		ProtocolVersion version) throws ProtocolException {
	RequestWrapper newRequest = new RequestWrapper(request);
	newRequest.setProtocolVersion(version);

	return newRequest;
}
 
Example #15
Source File: RequestProtocolCompliance.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private HttpRequest downgradeRequestTo(HttpRequest request,
		ProtocolVersion version) throws ProtocolException {
	RequestWrapper newRequest = new RequestWrapper(request);
	newRequest.setProtocolVersion(version);

	return newRequest;
}
 
Example #16
Source File: LibRequestDirector.java    From YiBo with Apache License 2.0 5 votes vote down vote up
private RequestWrapper wrapRequest(
        final HttpRequest request) throws ProtocolException {
    if (request instanceof HttpEntityEnclosingRequest) {
        return new EntityEnclosingRequestWrapper(
                (HttpEntityEnclosingRequest) request);
    } else {
        return new RequestWrapper(
                request);
    }
}
 
Example #17
Source File: ConditionalRequestBuilder.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * When a {@link HttpCacheEntry} is stale but 'might' be used as a response
 * to an {@link HttpRequest} we will attempt to revalidate the entry with
 * the origin. Build the origin {@link HttpRequest} here and return it.
 * 
 * @param request
 *            the original request from the caller
 * @param cacheEntry
 *            the entry that needs to be revalidated
 * @return the wrapped request
 * @throws ProtocolException
 *             when I am unable to build a new origin request.
 */
public HttpRequest buildConditionalRequest(HttpRequest request,
		HttpCacheEntry cacheEntry) throws ProtocolException {
	RequestWrapper wrapperRequest = new RequestWrapper(request);
	wrapperRequest.resetHeaders();
	Header eTag = cacheEntry.getFirstHeader(HeaderConstants.ETAG);
	if (eTag != null) {
		wrapperRequest.setHeader(HeaderConstants.IF_NONE_MATCH,
				eTag.getValue());
	}
	Header lastModified = cacheEntry
			.getFirstHeader(HeaderConstants.LAST_MODIFIED);
	if (lastModified != null) {
		wrapperRequest.setHeader(HeaderConstants.IF_MODIFIED_SINCE,
				lastModified.getValue());
	}
	boolean mustRevalidate = false;
	for (Header h : cacheEntry.getHeaders(HeaderConstants.CACHE_CONTROL)) {
		for (HeaderElement elt : h.getElements()) {
			if (HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE
					.equalsIgnoreCase(elt.getName())
					|| HeaderConstants.CACHE_CONTROL_PROXY_REVALIDATE
							.equalsIgnoreCase(elt.getName())) {
				mustRevalidate = true;
				break;
			}
		}
	}
	if (mustRevalidate) {
		wrapperRequest.addHeader("Cache-Control", "max-age=0");
	}
	return wrapperRequest;

}
 
Example #18
Source File: ConditionalRequestBuilder.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * When a {@link HttpCacheEntry} does not exist for a specific
 * {@link HttpRequest} we attempt to see if an existing
 * {@link HttpCacheEntry} is appropriate by building a conditional
 * {@link HttpRequest} using the variants' ETag values. If no such values
 * exist, the request is unmodified
 * 
 * @param request
 *            the original request from the caller
 * @param cacheEntry
 *            the entry that needs to be revalidated
 * @return the wrapped request
 * @throws ProtocolException
 *             when I am unable to build a new origin request.
 */
public HttpRequest buildConditionalRequestFromVariants(HttpRequest request,
		Set<HttpCacheEntry> variantEntries) throws ProtocolException {
	RequestWrapper wrapperRequest = new RequestWrapper(request);
	wrapperRequest.resetHeaders();

	// we do not support partial content so all etags are used
	StringBuilder etags = new StringBuilder();
	boolean first = true;
	for (HttpCacheEntry entry : variantEntries) {
		Header etagHeader = entry.getFirstHeader(HeaderConstants.ETAG);
		if (etagHeader != null) {
			if (first) {
				etags.append(etagHeader.getValue());
				first = false;
			} else {
				etags.append(",").append(etagHeader.getValue());
			}
		}
	}
	// if first is still true than no variants had a cache entry, return
	// unmodified wrapped request
	if (first) {
		return wrapperRequest;
	}

	wrapperRequest.setHeader(HeaderConstants.IF_NONE_MATCH,
			etags.toString());

	return wrapperRequest;
}
 
Example #19
Source File: EntityForwardingRedirectStrategyTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testGetRedirectHeadRequest() throws ProtocolException
{
    mockHeader();
    HttpHead httpRequest = new HttpHead(URI);
    HttpUriRequest actualRedirect = redirectStrategy.getRedirect(httpRequest, httpResponse, httpContext);
    assertEquals(REDIRECT_URI, actualRedirect.getURI().toString());
}
 
Example #20
Source File: SaveOriginalPostRequestTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private TestHttpClient createHttpClient() {
    TestHttpClient client = new TestHttpClient();

    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
            if (response.getStatusLine().getStatusCode() == StatusCodes.FOUND) {
                return true;
            }
            return super.isRedirected(request, response, context);
        }
    });

    return client;
}
 
Example #21
Source File: DAVRedirectStrategy.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    final String method = request.getRequestLine().getMethod();
    if(method.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
        return this.copyEntity(new HttpPut(this.getLocationURI(request, response, context)), request);
    }
    return super.getRedirect(request, response, context);
}
 
Example #22
Source File: CustomRedirectStrategy.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isRedirected(
        final HttpRequest request,
        final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }

    int statusCode = response.getStatusLine().getStatusCode();
    String method = request.getRequestLine().getMethod();
    Header locationHeader = response.getFirstHeader("location");
    switch (statusCode) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
        return isRedirectable(method) && locationHeader != null;
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        return isRedirectable(method);
    case HttpStatus.SC_SEE_OTHER:
        return true;
    default:
        return false;
    } //end of switch
}
 
Example #23
Source File: SeimiRedirectStrategy.java    From SeimiCrawler with Apache License 2.0 5 votes vote down vote up
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)&& request instanceof HttpRequestWrapper) {
        HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) request;
        httpRequestWrapper.setURI(uri);
        httpRequestWrapper.removeHeaders("Content-Length");
        return httpRequestWrapper;
    } else {
        return super.getRedirect(request,response,context);
    }
}
 
Example #24
Source File: AlwaysRedirectStrategy.java    From caravan with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
    if (super.isRedirected(request, response, context))
        return true;

    int statusCode = response.getStatusLine().getStatusCode();
    return isRedirected(statusCode);
}
 
Example #25
Source File: CustomRedirectStrategy.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public HttpUriRequest getRedirect(
        final HttpRequest request,
        final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = null;
    try {
        uri = getLocationURI(request, response, context);
    } catch (URISyntaxException ex) {
        Logger.getLogger(CustomRedirectStrategy.class.getName()).log(Level.SEVERE, null, ex);
    }
    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        return new HttpGet(uri);
    } else {
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                return copyEntity(new HttpPost(uri), request);
            } else if (method.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
                return copyEntity(new HttpPut(uri), request);
            } else if (method.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
                return new HttpDelete(uri);
            } else if (method.equalsIgnoreCase(HttpTrace.METHOD_NAME)) {
                return new HttpTrace(uri);
            } else if (method.equalsIgnoreCase(HttpOptions.METHOD_NAME)) {
                return new HttpOptions(uri);
            } else if (method.equalsIgnoreCase(HttpPatch.METHOD_NAME)) {
                return copyEntity(new HttpPatch(uri), request);
            }
        }
        return new HttpGet(uri);
    }
}
 
Example #26
Source File: AbstractRoutePlanner.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRoute determineRoute(final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException {
  Args.notNull(request, "Request");
  if (host == null) {
    throw new ProtocolException("Target host is not specified");
  }
  final HttpClientContext clientContext = HttpClientContext.adapt(context);
  final RequestConfig config = clientContext.getRequestConfig();
  int remotePort;
  if (host.getPort() <= 0) {
    try {
      remotePort = schemePortResolver.resolve(host);
    } catch (final UnsupportedSchemeException e) {
      throw new HttpException(e.getMessage());
    }
  } else
    remotePort = host.getPort();

  final Tuple<Inet4Address, Inet6Address> remoteAddresses = IpAddressTools.getRandomAddressesFromHost(host);
  final Tuple<InetAddress, InetAddress> addresses = determineAddressPair(remoteAddresses);

  final HttpHost target = new HttpHost(addresses.r, host.getHostName(), remotePort, host.getSchemeName());
  final HttpHost proxy = config.getProxy();
  final boolean secure = target.getSchemeName().equalsIgnoreCase("https");
  clientContext.setAttribute(CHOSEN_IP_ATTRIBUTE, addresses.l);
  log.debug("Setting route context attribute to {}", addresses.l);
  if (proxy == null) {
    return new HttpRoute(target, addresses.l, secure);
  } else {
    return new HttpRoute(target, addresses.l, proxy, secure);
  }
}
 
Example #27
Source File: NexusRedirectStrategy.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context)
    throws ProtocolException
{
  if (super.isRedirected(request, response, context)) {
    // code below comes from DefaultRedirectStrategy, as method super.getLocationURI cannot be used
    // since it modifies context state, and would result in false circular reference detection
    final Header locationHeader = response.getFirstHeader(LOCATION);
    if (locationHeader == null) {
      // got a redirect response, but no location header
      throw new ProtocolException("Received redirect response " + response.getStatusLine() +
          " but no location present");
    }

    // Some complication here as it appears that something may be null, but its not clear what was null
    final URI sourceUri = ((HttpUriRequest) request).getURI();
    final String sourceScheme = schemeOf(sourceUri);
    final String sourceHost = hostOf(sourceUri);

    final URI targetUri = createLocationURI(locationHeader.getValue());
    final String targetScheme = schemeOf(targetUri);
    final String targetHost = hostOf(targetUri);

    // FIXME: sourceUri might be relative while targetUri is always absolute, which can lead to
    // false-positive logging because the source scheme (null) differs from the target ("http")
    // One way to fix this is to resolve the relative sourceUri against the original proxy URL,
    // but this relies on access to the original configuration.

    // nag about redirection peculiarities, in any case
    if (!Objects.equals(sourceScheme, targetScheme)) {
      if (HTTP.equals(targetScheme)) {
        // security risk: HTTPS > HTTP downgrade, you are not safe as you think!
        log.debug("Downgrade from HTTPS to HTTP during redirection {} -> {}", sourceUri, targetUri);
      }
      else if ("https".equals(targetScheme) && Objects.equals(sourceHost, targetHost)) {
        // misconfiguration: your repository configured with wrong protocol and causes performance problems?
        log.debug("Protocol upgrade during redirection on same host {} -> {}", sourceUri, targetUri);
      }
    }

    // this logic below should trigger only for content fetches made by RRS retrieveItem
    // hence, we do this ONLY if the HttpRequest is "marked" as such request
    if (Boolean.TRUE == context.getAttribute(CONTENT_RETRIEVAL_MARKER_KEY)) {
      if (targetUri.getPath().endsWith("/")) {
        log.debug("Not following redirection to index {} -> {}", sourceUri, targetUri);
        return false;
      }
    }

    log.debug("Following redirection {} -> {}", sourceUri, targetUri);
    return true;
  }

  return false;
}
 
Example #28
Source File: TrustingUrlConnection.java    From RDFUnit with Apache License 2.0 4 votes vote down vote up
public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    lastRedirectedUri.add(super.getLocationURI(request, response, context));
    return lastRedirectedUri.get(lastRedirectedUri.size()-1);
}
 
Example #29
Source File: CachingHttpClient.java    From apigee-android-sdk with Apache License 2.0 4 votes vote down vote up
HttpResponse revalidateCacheEntry(HttpHost target, HttpRequest request,
		HttpContext context, HttpCacheEntry cacheEntry) throws IOException,
		ProtocolException {
	HttpRequest conditionalRequest = conditionalRequestBuilder
			.buildConditionalRequest(request, cacheEntry);

	Date requestDate = getCurrentDate();
	HttpResponse backendResponse = backend.execute(target,
			conditionalRequest, context);
	Date responseDate = getCurrentDate();

	final Header entryDateHeader = cacheEntry.getFirstHeader("Date");
	final Header responseDateHeader = backendResponse
			.getFirstHeader("Date");
	if (entryDateHeader != null && responseDateHeader != null) {
		try {
			Date entryDate = DateUtils
					.parseDate(entryDateHeader.getValue());
			Date respDate = DateUtils.parseDate(responseDateHeader
					.getValue());
			if (respDate.before(entryDate)) {
				HttpRequest unconditional = conditionalRequestBuilder
						.buildUnconditionalRequest(request, cacheEntry);
				requestDate = getCurrentDate();
				backendResponse = backend.execute(target, unconditional,
						context);
				responseDate = getCurrentDate();
			}
		} catch (DateParseException e) {
			// either backend response or cached entry did not have a valid
			// Date header, so we can't tell if they are out of order
			// according to the origin clock; thus we can skip the
			// unconditional retry recommended in 13.2.6 of RFC 2616.
		}
	}

	backendResponse.addHeader("Via", generateViaHeader(backendResponse));

	int statusCode = backendResponse.getStatusLine().getStatusCode();
	if (statusCode == HttpStatus.SC_NOT_MODIFIED
			|| statusCode == HttpStatus.SC_OK) {
		cacheUpdates.getAndIncrement();
		setResponseStatus(context, CacheResponseStatus.VALIDATED);
	}

	if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
		HttpCacheEntry updatedEntry = responseCache.updateCacheEntry(
				target, request, cacheEntry, backendResponse, requestDate,
				responseDate);
		if (suitabilityChecker.isConditional(request)
				&& suitabilityChecker.allConditionalsMatch(request,
						updatedEntry, new Date())) {
			return responseGenerator
					.generateNotModifiedResponse(updatedEntry);
		}
		return responseGenerator.generateResponse(updatedEntry);
	}

	return handleBackendResponse(target, conditionalRequest, requestDate,
			responseDate, backendResponse);
}
 
Example #30
Source File: HtmlUnitRedirectStrategie.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isRedirected(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    return super.isRedirected(request, response, context) && response.getFirstHeader("location") != null;
}