Java Code Examples for org.apache.http.client.protocol.HttpClientContext#getTargetHost()

The following examples show how to use org.apache.http.client.protocol.HttpClientContext#getTargetHost() . 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: HttpClientManagerImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates absolute request URI with full path from passed in context.
 */
@Nonnull
private URI getRequestURI(final HttpContext context) {
  final HttpClientContext clientContext = HttpClientContext.adapt(context);
  final HttpRequest httpRequest = clientContext.getRequest();
  final HttpHost target = clientContext.getTargetHost();
  try {
    URI uri;
    if (httpRequest instanceof HttpUriRequest) {
      uri = ((HttpUriRequest) httpRequest).getURI();
    }
    else {
      uri = URI.create(httpRequest.getRequestLine().getUri());
    }
    return uri.isAbsolute() ? uri : URIUtils.resolve(URI.create(target.toURI()), uri);
  }
  catch (Exception e) {
    log.warn("Could not create absolute request URI", e);
    return URI.create(target.toURI());
  }
}
 
Example 2
Source File: HttpClientConfigurator.java    From bintray-client-java with Apache License 2.0 6 votes vote down vote up
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    AuthState authState = clientContext.getTargetAuthState();

    // If there's no auth scheme available yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
        HttpHost targetHost = clientContext.getTargetHost();
        Credentials creds = credsProvider.getCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()));
        if (creds != null) {
            authState.update(new BasicScheme(), creds);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("PreemptiveAuthInterceptor: No credentials for preemptive authentication");
            }
        }
    }
}
 
Example 3
Source File: TracingProtocolExec.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public CloseableHttpResponse execute(HttpRoute route,
  org.apache.http.client.methods.HttpRequestWrapper req,
  HttpClientContext context, HttpExecutionAware execAware)
  throws IOException, HttpException {
  HttpRequestWrapper request = new HttpRequestWrapper(req, context.getTargetHost());
  Span span = tracer.nextSpan(httpSampler, request);
  context.setAttribute(Span.class.getName(), span);

  CloseableHttpResponse response = null;
  Throwable error = null;
  try (SpanInScope ws = tracer.withSpanInScope(span)) {
    return response = protocolExec.execute(route, req, context, execAware);
  } catch (Throwable e) {
    error = e;
    throw e;
  } finally {
    handler.handleReceive(new HttpResponseWrapper(response, context, error), span);
  }
}
 
Example 4
Source File: PreemptiveAuthHttpRequestInterceptor.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
  HttpClientContext clientContext = HttpClientContext.adapt(context);
  AuthState authState = clientContext.getTargetAuthState();
  if (authState.getAuthScheme() == null) {
    CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
    HttpHost targetHost = clientContext.getTargetHost();
    Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
    if (creds != null) {
      authState.update(new BasicScheme(), creds);
    }
  }
}
 
Example 5
Source File: TracingProtocolExec.java    From brave with Apache License 2.0 5 votes vote down vote up
HttpResponseWrapper(@Nullable HttpResponse response, HttpClientContext context,
  @Nullable Throwable error) {
  HttpRequest request = context.getRequest();
  HttpHost target = context.getTargetHost();
  this.request = request != null ? new HttpRequestWrapper(request, target) : null;
  this.response = response;
  this.error = error;
}
 
Example 6
Source File: HttpGetter.java    From commafeed with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param url
 *            the url to retrive
 * @param lastModified
 *            header we got last time we queried that url, or null
 * @param eTag
 *            header we got last time we queried that url, or null
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 * @throws NotModifiedException
 *             if the url hasn't changed since we asked for it last time
 */
public HttpResult getBinary(String url, String lastModified, String eTag, int timeout) throws ClientProtocolException, IOException,
		NotModifiedException {
	HttpResult result = null;
	long start = System.currentTimeMillis();

	CloseableHttpClient client = newClient(timeout);
	CloseableHttpResponse response = null;
	try {
		HttpGet httpget = new HttpGet(url);
		HttpClientContext context = HttpClientContext.create();

		httpget.addHeader(HttpHeaders.ACCEPT_LANGUAGE, ACCEPT_LANGUAGE);
		httpget.addHeader(HttpHeaders.PRAGMA, PRAGMA_NO_CACHE);
		httpget.addHeader(HttpHeaders.CACHE_CONTROL, CACHE_CONTROL_NO_CACHE);
		httpget.addHeader(HttpHeaders.USER_AGENT, userAgent);

		if (lastModified != null) {
			httpget.addHeader(HttpHeaders.IF_MODIFIED_SINCE, lastModified);
		}
		if (eTag != null) {
			httpget.addHeader(HttpHeaders.IF_NONE_MATCH, eTag);
		}

		try {
			response = client.execute(httpget, context);
			int code = response.getStatusLine().getStatusCode();
			if (code == HttpStatus.SC_NOT_MODIFIED) {
				throw new NotModifiedException("'304 - not modified' http code received");
			} else if (code >= 300) {
				throw new HttpResponseException(code, "Server returned HTTP error code " + code);
			}

		} catch (HttpResponseException e) {
			if (e.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
				throw new NotModifiedException("'304 - not modified' http code received");
			} else {
				throw e;
			}
		}
		Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
		String lastModifiedHeaderValue = lastModifiedHeader == null ? null : StringUtils.trimToNull(lastModifiedHeader.getValue());
		if (lastModifiedHeaderValue != null && StringUtils.equals(lastModified, lastModifiedHeaderValue)) {
			throw new NotModifiedException("lastModifiedHeader is the same");
		}

		Header eTagHeader = response.getFirstHeader(HttpHeaders.ETAG);
		String eTagHeaderValue = eTagHeader == null ? null : StringUtils.trimToNull(eTagHeader.getValue());
		if (eTag != null && StringUtils.equals(eTag, eTagHeaderValue)) {
			throw new NotModifiedException("eTagHeader is the same");
		}

		HttpEntity entity = response.getEntity();
		byte[] content = null;
		String contentType = null;
		if (entity != null) {
			content = EntityUtils.toByteArray(entity);
			if (entity.getContentType() != null) {
				contentType = entity.getContentType().getValue();
			}
		}

		String urlAfterRedirect = url;
		if (context.getRequest() instanceof HttpUriRequest) {
			HttpUriRequest req = (HttpUriRequest) context.getRequest();
			HttpHost host = context.getTargetHost();
			urlAfterRedirect = req.getURI().isAbsolute() ? req.getURI().toString() : host.toURI() + req.getURI();
		}

		long duration = System.currentTimeMillis() - start;
		result = new HttpResult(content, contentType, lastModifiedHeaderValue, eTagHeaderValue, duration, urlAfterRedirect);
	} finally {
		IOUtils.closeQuietly(response);
		IOUtils.closeQuietly(client);
	}
	return result;
}