List of usage examples for org.apache.http.client.protocol HttpClientContext create
public static HttpClientContext create()
From source file:org.jboss.teiid.quickstart.PortfolioClient.java
public void resteasyHttpBackendClient() { System.out.println("\nResteasy Client API with HTTP client as engine"); HttpHost targetHost = new HttpHost("localhost", 8080, "http"); // 1. Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // 2. Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // 3. Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // 4. Create client executor and proxy HttpClientBuilder builder = HttpClientBuilder.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope scope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD); credsProvider.setCredentials(scope, credentials); builder.setDefaultCredentialsProvider(credsProvider); HttpClient httpClient = builder.build(); // 5. Create ResteasyClient with http client as engine ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, localContext); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); // 6. Execute Rest call via ResteasyClient String authString = getBasicAuthentication(); for (String api : apis) { ResteasyWebTarget target = client.target(api); Response response = target.request().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, authString).get(); if (response.getStatus() == 200) { String value = response.readEntity(String.class); System.out.println(value); response.close();//from w ww .j av a 2 s.co m } else { handleError(response); } } }
From source file:io.crate.rest.AdminUIHttpIntegrationTest.java
List<URI> getAllRedirectLocations(String uri, Header[] headers) throws IOException { CloseableHttpResponse response = null; try {/*w w w . j a v a 2 s. c om*/ HttpClientContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(String.format(Locale.ENGLISH, "http://%s:%s/%s", address.getHostName(), address.getPort(), uri)); if (headers != null) { httpGet.setHeaders(headers); } response = httpClient.execute(httpGet, context); // get all redirection locations return context.getRedirectLocations(); } finally { if (response != null) { response.close(); } } }
From source file:org.modelio.vbasic.net.ApacheUriConnection.java
@objid("f8e1a3e4-45b3-4065-8838-90de7fe64eaa") private void openConnection() throws IOException, IllegalStateException { this.context = HttpClientContext.create(); CredentialsProvider credsProvider = new SystemDefaultCredentialsProvider(); this.context.setCredentialsProvider(credsProvider); if (this.auth != null) { switch (this.auth.getSchemeId()) { case UserPasswordAuthData.USERPASS_SCHEME_ID: UserPasswordAuthData authData = (UserPasswordAuthData) this.auth; if (authData.getUser() == null) throw new ClientProtocolException(this.uri + ": User name may not be null."); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authData.getUser(), authData.getPassword()); AuthScope authscope = new AuthScope(this.uri.getHost(), AuthScope.ANY_PORT); credsProvider.setCredentials(authscope, credentials); break; case NoneAuthData.AUTH_NONE_SCHEME_ID: break; default:/*from www .j a v a2 s .co m*/ throw new UnknownServiceException(this.auth + " not supported for " + this.uri); } } /** support different proxy */ configProxy(credsProvider); getRequest().setConfig(this.configBuilder.build()); try { this.res = httpclient.execute(getRequest(), this.context); int statusCode = this.res.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { // Try to get content now to get an exception on failure immediately this.res.getEntity().getContent(); } else { handleConnectionFailure(); } } catch (ClientProtocolException e) { throw new IOException(e.getLocalizedMessage(), e); } }
From source file:org.nebula.framework.client.NebulaRestClient.java
private HttpClientContext createPreemptiveBasicAuthentication(String accessId, String password) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(accessId, password)); AuthCache authCache = new BasicAuthCache(); authCache.put(target, new BasicScheme()); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache);// ww w .j a v a2 s . c om return context; }
From source file:com.certivox.net.HTTPConnector.java
public HTTPResponse sendRequest(String serviceURL, String http_method, String requestBody, Hashtable<String, String> requestProperties) throws IOException { HttpRequestBase httpRequest = HttpRequestFactory.createRequest(serviceURL, http_method, requestBody, requestProperties);/*w w w . j a v a 2 s . c o m*/ CloseableHttpResponse response = httpClient.execute(httpRequest, HttpClientContext.create()); try { HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return new HTTPResponse(response.getStatusLine().getStatusCode(), StringUtils.convertStreamToString(is)); } finally { is.close(); } } finally { response.close(); } }
From source file:com.fourspaces.couchdb.Session.java
/** * Constructor for obtaining a Session with an HTTP-AUTH username/password * and (optionally) a secure connection This isn't supported by CouchDB - * you need a proxy in front to use this * * @param host - hostname//from w ww .j a va 2 s. co m * @param port - port to use * @param user - username * @param pass - password * @param usesAuth * @param secure - use an SSL connection? */ public Session(String host, int port, String user, String pass, boolean usesAuth, boolean secure) { this.host = host; this.port = port; this.user = user; this.pass = pass; this.usesAuth = usesAuth; this.secure = secure; PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf).register("https", sslsf).build(); this.connManager = new PoolingHttpClientConnectionManager(r); this.requestConfig = RequestConfig.custom().setConnectTimeout(15 * 1000).setSocketTimeout((30 * 1000)) .setAuthenticationEnabled(usesAuth).build(); this.httpContext = HttpClientContext.create(); if (user != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); this.httpContext.setCredentialsProvider(credsProvider); } this.httpClient = createHttpClient(); }
From source file:org.ops4j.pax.web.itest.DigestAuthenticationTest.java
@Test public void shouldPermitUnauthenticatedAccessToUnprotectedResource() throws Exception { String path = String.format("http://localhost:%d/digest/plain.txt", getHttpPort()); HttpClientContext context = HttpClientContext.create(); CloseableHttpClient client = HttpClients.custom().build(); HttpGet httpGet = new HttpGet(path); HttpResponse response = client.execute(httpGet, context); int statusCode = response.getStatusLine().getStatusCode(); assertThat(statusCode, is(200));//w w w . j a v a 2s . c o m String text = EntityUtils.toString(response.getEntity()); assertThat(text, containsString("plain text")); }
From source file:se.skltp.adapterservices.druglogistics.dosdispensing.RetryComponent.java
/** * Main method of the component. Make a http(s) post-request and retries a number of times before giving up. If the request casue a soap-fault it is sent back as the response (but with no handling of http-status, e.g. setting it to 500) * /*from www . j av a 2 s .co m*/ * @param eventContext */ @Override public Object onCall(MuleEventContext eventContext) { // Get the request from the mule message MuleMessage message = eventContext.getMessage(); String request = message.getPayload().toString(); EventLoggerWrapper eventLog = new EventLoggerWrapper(context, message); try { // Setup HTTP stuff HttpClientContext context = HttpClientContext.create(); HttpClient httpClient = setupHttpClient(); HttpPost httpPost = setupHttpPost(setupHttpRequestEntity(request)); // Perform the processing including retries log.debug("Request: [{}]", request); String response = performPostWithRetries(eventLog, context, httpClient, httpPost); log.debug("Response: [{}]", response); // Set response and bail out message.setPayload(response); return message; } catch (SoapFaultInPayloadException sfipe) { // We got a soap fault from the service producer, set http.status according to RIV-TA 2.x (actually WS-I BP 1.1) and return the soap-fault as the response again according to RIV-TA 2.x (WS-I BP 1.1) eventLog.logError(sfipe, "Request still failed after max retries (" + maxRetries + "), giving up! SOAP Fault from producer passed back to consumer"); message.setOutboundProperty("http.status", 500); return sfipe.getSoapFault(); } }
From source file:org.callimachusproject.client.HttpClientRedirectTest.java
@Test public void testRedirectLocationsReset() throws Exception { register("*", new SimpleService()); register("/People.htm", new HttpRequestHandler() { public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { response.setStatusCode(HttpStatus.SC_MOVED_PERMANENTLY); response.setHeader("Location", "/people.html"); final StringEntity entity = new StringEntity("Whatever"); response.setEntity(entity);/*w w w . j a va2s. com*/ } }); final HttpHost target = getServerHttp(); final HttpGet httpget = new HttpGet("/People.htm"); final HttpClientContext context = HttpClientContext.create(); this.httpclient.execute(target, httpget, context); // this checks that the context was properly reset final HttpResponse response = this.httpclient.execute(target, httpget, context); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); final HttpRequest request = context.getRequest(); Assert.assertEquals("/people.html", request.getRequestLine().getUri()); final URI uri = new URIBuilder().setHost(target.getHostName()).setPort(target.getPort()) .setScheme(target.getSchemeName()).setPath("/people.html").build(); final URI location = getHttpLocation(httpget, context); Assert.assertEquals(uri, location); }
From source file:de.adorsys.oauth.loginmodule.HTTPAuthenticationLoginModule.java
private boolean authenticate(String username, String password) throws LoginException { HttpHost targetHost = new HttpHost(restEndpoint.getHost(), restEndpoint.getPort(), restEndpoint.getScheme());/*from w w w . j av a2 s . co m*/ CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(Consts.UTF_8); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); HttpGet httpGet = new HttpGet(restEndpoint); CloseableHttpResponse userInfoResponse = null; try { userInfoResponse = HTTP_CLIENT.execute(httpGet, context); if (userInfoResponse.getStatusLine().getStatusCode() != 200) { LOG.error("Authentication failed for user {}, restEndpoint {} HTTP Status {}", username, restEndpoint.toASCIIString(), userInfoResponse.getStatusLine()); throw new LoginException("Authentication failed for user " + username + ", restEndpoint " + restEndpoint.toASCIIString() + " HTTP Status " + userInfoResponse.getStatusLine()); } String userInfoJson = readUserInfo(userInfoResponse); JSONObject userInfo = new JSONObject(userInfoJson); String principalId = userInfo.getString("principal"); if (principalId == null) { LOG.error("could not read field 'principal' for user {}. Response: {}", username, userInfoJson); throw new LoginException( "could not read field 'principal' for user " + username + ". Response: " + userInfoJson); } JSONArray roles = userInfo.getJSONArray("roles"); populateSubject(principalId, roles); // we put them to shared stated that other login providers can also // authenticate sharedState.put("javax.security.auth.login.name", principalId); sharedState.put("javax.security.auth.login.password", password); } catch (IOException e) { throw new IllegalStateException("problem on http backend authentication", e); } finally { if (userInfoResponse != null) { try { userInfoResponse.close(); } catch (IOException e) { ; // NOOP } } } return true; }