List of usage examples for org.apache.http.client.protocol HttpClientContext setTargetHost
public void setTargetHost(HttpHost httpHost)
From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl.java
@Override public byte[] send(byte[] request) { HttpClientContext context = HttpClientContext.create(); context.setTargetHost(host); context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); context.setAuthCache(authCache);/*from w w w .ja va2 s. c om*/ ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM); // Create the client with the AuthSchemeRegistry and manager HttpPost post = new HttpPost(toURI(url)); post.setEntity(entity); try (CloseableHttpResponse response = client.execute(post, context)) { final int statusCode = response.getStatusLine().getStatusCode(); if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) { return EntityUtils.toByteArray(response.getEntity()); } throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode); } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.debug("Failed to execute HTTP request", e); throw new RuntimeException(e); } }
From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java
public byte[] send(byte[] request) { while (true) { HttpClientContext context = HttpClientContext.create(); context.setTargetHost(host); // Set the credentials if they were provided. if (null != this.credentials) { context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); context.setAuthCache(authCache); }/*ww w.ja v a 2 s .c o m*/ ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM); // Create the client with the AuthSchemeRegistry and manager HttpPost post = new HttpPost(uri); post.setEntity(entity); try (CloseableHttpResponse response = execute(post, context)) { final int statusCode = response.getStatusLine().getStatusCode(); if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) { return EntityUtils.toByteArray(response.getEntity()); } else if (HttpURLConnection.HTTP_UNAVAILABLE == statusCode) { LOG.debug("Failed to connect to server (HTTP/503), retrying"); continue; } throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode); } catch (NoHttpResponseException e) { // This can happen when sitting behind a load balancer and a backend server dies LOG.debug("The server failed to issue an HTTP response, retrying"); continue; } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.debug("Failed to execute HTTP request", e); throw new RuntimeException(e); } } }
From source file:org.apache.hadoop.hbase.http.TestSpnegoHttpServer.java
@Test public void testAllowedClient() throws Exception { // Create the subject for the client final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab); final Set<Principal> clientPrincipals = clientSubject.getPrincipals(); // Make sure the subject has a principal assertFalse(clientPrincipals.isEmpty()); // Get a TGT for the subject (might have many, different encryption types). The first should // be the default encryption type. Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class); assertFalse(privateCredentials.isEmpty()); KerberosTicket tgt = privateCredentials.iterator().next(); assertNotNull(tgt);//from w w w .j av a2 s . c om // The name of the principal final String principalName = clientPrincipals.iterator().next().getName(); // Run this code, logged in as the subject (the client) HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() { @Override public HttpResponse run() throws Exception { // Logs in with Kerberos via GSS GSSManager gssManager = GSSManager.getInstance(); // jGSS Kerberos login constant Oid oid = new Oid("1.2.840.113554.1.2.2"); GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME); GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY); HttpClientContext context = HttpClientContext.create(); Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential)); URL url = new URL(getServerURL(server), "/echo?a=b"); context.setTargetHost(new HttpHost(url.getHost(), url.getPort())); context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); HttpGet get = new HttpGet(url.toURI()); return client.execute(get, context); } }); assertNotNull(resp); assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode()); assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim()); }
From source file:net.yacy.cora.protocol.http.HTTPClient.java
private void execute(final HttpUriRequest httpUriRequest, final boolean concurrent) throws IOException { final HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(reqConfBuilder.build()); if (this.host != null) context.setTargetHost(new HttpHost(this.host)); setHeaders(httpUriRequest);//from ww w . java 2s . co m // statistics storeConnectionInfo(httpUriRequest); // execute the method; some asserts confirm that that the request can be send with Content-Length and is therefore not terminated by EOF if (httpUriRequest instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest hrequest = (HttpEntityEnclosingRequest) httpUriRequest; final HttpEntity entity = hrequest.getEntity(); assert entity != null; //assert !entity.isChunked(); //assert entity.getContentLength() >= 0; assert !hrequest.expectContinue(); } final String initialThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("HTTPClient-" + httpUriRequest.getURI()); final long time = System.currentTimeMillis(); try { if (concurrent) { FutureTask<CloseableHttpResponse> t = new FutureTask<CloseableHttpResponse>( new Callable<CloseableHttpResponse>() { @Override public CloseableHttpResponse call() throws ClientProtocolException, IOException { final CloseableHttpClient client = clientBuilder.build(); CloseableHttpResponse response = client.execute(httpUriRequest, context); return response; } }); executor.execute(t); try { this.httpResponse = t.get(this.timeout, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw e.getCause(); } catch (Throwable e) { } try { t.cancel(true); } catch (Throwable e) { } if (this.httpResponse == null) throw new IOException("timout to client after " + this.timeout + "ms" + " for url " + httpUriRequest.getURI().toString()); } else { final CloseableHttpClient client = clientBuilder.build(); this.httpResponse = client.execute(httpUriRequest, context); } this.httpResponse.setHeader(HeaderFramework.RESPONSE_TIME_MILLIS, Long.toString(System.currentTimeMillis() - time)); } catch (final Throwable e) { ConnectionInfo.removeConnection(httpUriRequest.hashCode()); httpUriRequest.abort(); if (this.httpResponse != null) this.httpResponse.close(); //e.printStackTrace(); throw new IOException( "Client can't execute: " + (e.getCause() == null ? e.getMessage() : e.getCause().getMessage()) + " duration=" + Long.toString(System.currentTimeMillis() - time) + " for url " + httpUriRequest.getURI().toString()); } finally { /* Restore the thread initial name */ Thread.currentThread().setName(initialThreadName); } }
From source file:org.apache.hadoop.hbase.rest.TestSecureRESTServer.java
private Pair<CloseableHttpClient, HttpClientContext> getClient() { HttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(); HttpHost host = new HttpHost("localhost", REST_TEST.getServletPort()); Registry<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE); AuthCache authCache = new BasicAuthCache(); CloseableHttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry) .setConnectionManager(pool).build(); HttpClientContext context = HttpClientContext.create(); context.setTargetHost(host); context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); context.setAuthCache(authCache);//from w w w .j a v a 2s. c o m return new Pair<>(client, context); }