public static void main(String... args) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); NTCredentials creds = new NTCredentials("abhisheks", "abhiProJul17", "", ""); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); HttpHost target = new HttpHost("apps.prorigo.com", 80, "http"); // Make sure the same context is used to execute logically related requests HttpContext localContext = new BasicHttpContext(); // Execute a cheap method first. This will trigger NTLM authentication HttpGet httpget = new HttpGet("/conference/Booking"); HttpResponse response = httpclient.execute(target, httpget, localContext); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); }
@Override public CloseableHttpAsyncClient generateClient () { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope (AuthScope.ANY), new UsernamePasswordCredentials(serviceUser, servicePass)); RequestConfig rqconf = RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT) .setSocketTimeout(Timeouts.SOCKET_TIMEOUT) .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT) .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT) .build(); CloseableHttpAsyncClient res = HttpAsyncClients.custom () .setDefaultCredentialsProvider (credsProvider) .setDefaultRequestConfig(rqconf) .build (); res.start (); return res; }
public void afterPropertiesSet() throws UnsupportedEncodingException { Collection<Header> defaultHeaders = new ArrayList<Header>(); Header header = new BasicHeader("Authorization", "Basic " + BaseEncoding.base64().encode("apollo:".getBytes("UTF-8"))); defaultHeaders.add(header); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("apollo", "")); CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .setDefaultHeaders(defaultHeaders).build(); restTemplate = new RestTemplate(httpMessageConverters.getConverters()); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); requestFactory.setConnectTimeout(portalConfig.connectTimeout()); requestFactory.setReadTimeout(portalConfig.readTimeout()); restTemplate.setRequestFactory(requestFactory); }
protected HttpContext createHttpContext(HttpProxy httpProxy, CookieStore cookieStore) { HttpContext httpContext = new HttpClientContext(); if (cookieStore != null) { httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); } if (httpProxy != null && StringUtils.isNotBlank(httpProxy.getUsername())) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(httpProxy.getHost(), httpProxy.getPort()), new UsernamePasswordCredentials(httpProxy.getUsername(), httpProxy.getPassword())); httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider); } return httpContext; }
@Override public void setAuth(SensorThingsService service) { try { CredentialsProvider credsProvider = new BasicCredentialsProvider(); URL url = service.getEndpoint().toURL(); credsProvider.setCredentials( new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(editorUsername.getValue(), editorPassword.getValue())); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); service.setClient(httpclient); } catch (MalformedURLException ex) { LOGGER.error("Failed to initialise basic auth.", ex); } }
private static AbstractHttpClient createHTTPClient() { AbstractHttpClient client = new DefaultHttpClient(); String proxyHost = System.getProperty("https.proxyHost", ""); if (!proxyHost.isEmpty()) { int proxyPort = Integer.parseInt(System.getProperty("https.proxyPort", "-1")); log.info("Using proxy " + proxyHost + ":" + proxyPort); HttpParams params = client.getParams(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); String proxyUser = System.getProperty(JMeter.HTTP_PROXY_USER, JMeterUtils.getProperty(JMeter.HTTP_PROXY_USER)); if (proxyUser != null) { log.info("Using authenticated proxy with username: " + proxyUser); String proxyPass = System.getProperty(JMeter.HTTP_PROXY_PASS, JMeterUtils.getProperty(JMeter.HTTP_PROXY_PASS)); String localHost; try { localHost = InetAddress.getLocalHost().getCanonicalHostName(); } catch (Throwable e) { log.error("Failed to get local host name, defaulting to 'localhost'", e); localHost = "localhost"; } AuthScope authscope = new AuthScope(proxyHost, proxyPort); String proxyDomain = JMeterUtils.getPropDefault("http.proxyDomain", ""); NTCredentials credentials = new NTCredentials(proxyUser, proxyPass, localHost, proxyDomain); client.getCredentialsProvider().setCredentials(authscope, credentials); } } return client; }
protected CloseableHttpClient constructHttpClient() throws IOException { RequestConfig config = RequestConfig.custom() .setConnectTimeout(20 * 1000) .setConnectionRequestTimeout(20 * 1000) .setSocketTimeout(20 * 1000) .setMaxRedirects(20) .build(); URL mmsc = new URL(apn.getMmsc()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (apn.hasAuthentication()) { credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword())); } return HttpClients.custom() .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()) .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT)) .setConnectionManager(new BasicHttpClientConnectionManager()) .setDefaultRequestConfig(config) .setDefaultCredentialsProvider(credsProvider) .build(); }
private HttpClientContext prepareContext() { HttpHost targetHost = new HttpHost(serverConfig.getServerName(), serverConfig.getPort(), serverConfig.isUseHTTPS() ? "https" : "http"); AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(serverConfig.getUserName(), serverConfig.getPassword()); credsProvider.setCredentials(AuthScope.ANY, credentials); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); return context; }
@Override public CloseableHttpAsyncClient generateClient () { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope (AuthScope.ANY), new UsernamePasswordCredentials(username, password)); RequestConfig rqconf = RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT) .setSocketTimeout(Timeouts.SOCKET_TIMEOUT) .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT) .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT) .build(); CloseableHttpAsyncClient res = HttpAsyncClients.custom () .setDefaultCredentialsProvider (credsProvider) .setDefaultRequestConfig(rqconf) .build (); res.start (); return res; }
private HttpContext httpContext() { BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider(); if (isNotBlank(this.username) && this.password != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); HttpHost httpHost = HttpHost.create(this.rootConfluenceUrl); AuthScope authScope = new AuthScope(httpHost); basicCredentialsProvider.setCredentials(authScope, credentials); BasicAuthCache basicAuthCache = new BasicAuthCache(); basicAuthCache.put(httpHost, new BasicScheme()); HttpClientContext httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(basicCredentialsProvider); httpClientContext.setAuthCache(basicAuthCache); return httpClientContext; } else { return null; } }
/** * Find matching {@link Credentials credentials} for the given authentication scope. * * @param map the credentials hash map * @param authscope the {@link AuthScope authentication scope} * @return the credentials * */ private static Credentials matchCredentials( final Map<AuthScope, Credentials> map, final AuthScope authscope) { // see if we get a direct hit Credentials creds = map.get(authscope); if (creds == null) { // Nope. // Do a full scan int bestMatchFactor = -1; AuthScope bestMatch = null; for (AuthScope current: map.keySet()) { int factor = authscope.match(current); if (factor > bestMatchFactor) { bestMatchFactor = factor; bestMatch = current; } } if (bestMatch != null) { creds = map.get(bestMatch); } } return creds; }
public static void deleteRESTUser(String usrName){ try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpDelete delete = new HttpDelete("http://"+host+":8002/manage/v2/users/"+usrName); HttpResponse response = client.execute(delete); if(response.getStatusLine().getStatusCode()== 202){ Thread.sleep(3500); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public static void deleteUserRole(String roleName){ try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpDelete delete = new HttpDelete("http://"+host+":8002/manage/v2/roles/"+roleName); HttpResponse response = client.execute(delete); if(response.getStatusLine().getStatusCode()== 202){ Thread.sleep(3500); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public static void deleteRESTServerWithDB(String restServerName) { try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpDelete delete = new HttpDelete("http://"+host+":8002/v1/rest-apis/"+restServerName+"?include=content&include=modules"); HttpResponse response = client.execute(delete); if(response.getStatusLine().getStatusCode()== 202){ Thread.sleep(9500); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public static void loadBug18993(){ try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8011), new UsernamePasswordCredentials("admin", "admin")); String document ="<foo>a space b</foo>"; String perm = "perm:rest-writer=read&perm:rest-writer=insert&perm:rest-writer=update&perm:rest-writer=execute"; HttpPut put = new HttpPut("http://"+host+":8011/v1/documents?uri=/a%20b&"+perm); put.addHeader("Content-type", "application/xml"); put.setEntity(new StringEntity(document)); HttpResponse response = client.execute(put); HttpEntity respEntity = response.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public static void setAuthentication(String level,String restServerName) throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); String body = "{\"authentication\": \""+level+"\"}"; HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(body)); HttpResponse response2 = client.execute(put); HttpEntity respEntity = response2.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }
public static void setDefaultUser(String usr,String restServerName) throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); String body = "{\"default-user\": \""+usr+"\"}"; HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(body)); HttpResponse response2 = client.execute(put); HttpEntity respEntity = response2.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }
public static void setPathRangeIndexInDatabase(String dbName, JsonNode jnode) throws IOException { try { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpPut put = new HttpPut("http://"+host+":8002"+ "/manage/v2/databases/"+dbName+"/properties?format=json"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(jnode.toString())); HttpResponse response = client.execute(put); HttpEntity respEntity = response.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) { HttpClientBuilder clientBuilder = HttpClients.custom() .useSystemProperties() .setProxy(new HttpHost(proxyHost, proxyPort, "http")); if (credentials != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials); clientBuilder.setDefaultCredentialsProvider(credsProvider); Loggers.SERVER.debug("MsTeamsNotification ::using proxy credentials " + credentials.getUserPrincipal().getName()); } this.client = clientBuilder.build(); } }
@Override protected HttpHost determineProxy(HttpHost host, HttpRequest request, HttpContext context) throws HttpException { HttpClientContext httpClientContext = HttpClientContext.adapt(context); Proxy proxy = proxyPlanner.determineProxy(host, request, context, ipPool, crawlerSession); if (proxy == null) { return null; } if (log.isDebugEnabled()) { log.debug("{} 当前使用IP为:{}:{}", host.getHostName(), proxy.getIp(), proxy.getPort()); } context.setAttribute(VSCRAWLER_AVPROXY_KEY, proxy); if (proxy.getAuthenticationHeaders() != null) { for (Header header : proxy.getAuthenticationHeaders()) { request.addHeader(header); } } if (StringUtils.isNotEmpty(proxy.getUsername()) && StringUtils.isNotEmpty(proxy.getPassword())) { BasicCredentialsProvider credsProvider1 = new BasicCredentialsProvider(); httpClientContext.setCredentialsProvider(credsProvider1); credsProvider1.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword())); } return new HttpHost(proxy.getIp(), proxy.getPort()); }
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute("http.auth.target-scope"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute("http.auth" + ".credentials-provider"); HttpHost targetHost = (HttpHost) context.getAttribute("http.target_host"); if (authState.getAuthScheme() == null) { Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName (), targetHost.getPort())); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } }
@Before public void setUp() throws Exception { /** * 如果es集群安装了x-pack插件则以此种方式连接集群 * 1. java客户端的方式是以tcp协议在9300端口上进行通信 * 2. http客户端的方式是以http协议在9200端口上进行通信 */ Settings settings = Settings.builder(). put("xpack.security.user", "elastic:changeme").build(); client = new PreBuiltXPackTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); elasticsearchTemplate = new ElasticsearchTemplate(client); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "changeme")); restClient = RestClient.builder(new HttpHost("localhost",9200,"http")) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }).build(); }
public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) { prop = decrypt(prop); String proxyHost = prop.getProperty("proxyHost"); int proxyPort = Integer.valueOf(prop.getProperty("proxyPort")); String proxyUserDomain = prop.getProperty("proxyUserDomain"); String proxyUser = prop.getProperty("proxyUser"); String proxyPassword = prop.getProperty("proxyPassword"); HttpClientBuilder builder = HttpClientBuilder.create(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain)); if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) { credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())), new UsernamePasswordCredentials(proxyUser, proxyPassword)); } builder.setProxy(proxy); builder.setDefaultCredentialsProvider(credsProvider); HttpClient.Factory factory = new SimpleHttpClientFactory(builder); return new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory); }
private SystemDefaultHttpClient getHttpClient() { final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient(); httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true)); Credentials use_jaas_creds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; httpClient.getCredentialsProvider().setCredentials( AuthScope.ANY, use_jaas_creds); return httpClient; }
@Override public void setUsernamePassword(AuthenticationType authType, String username, String password) { this.credentials = new UsernamePasswordCredentials( Objects.requireNonNull(username), Objects.requireNonNull(password)); this.credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create(); switch (authType) { case BASIC: authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); break; case DIGEST: authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; default: throw new IllegalArgumentException("Unsupported authentiation type: " + authType); } this.authRegistry = authRegistryBuilder.build(); }
private static void buildClient() { if ( USE_PROXY ) { ClientConfig config = new ClientConfig(); config.connectorProvider(new ApacheConnectorProvider()); CredentialsProvider credentials = new BasicCredentialsProvider(); credentials.setCredentials(AuthScope.ANY, new NTCredentials(PROXY_USER, PROXY_PASS, null, PROXY_DOMAIN)); config.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentials); config.property(ClientProperties.PROXY_URI, PROXY_PROTOCOL + PROXY_SERVER); client = ClientBuilder.newClient(config); } else client = ClientBuilder.newClient(); }
public HttpClientConfigurer basicAuthCredentials(String username, String password) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); useBasicAuth = true; return this; }
@PostConstruct public void init() { objectMapper = new ObjectMapper(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); if (StringUtils.hasText(camundaUser)) { final BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(camundaUser, camundaPass)); clientBuilder.setDefaultCredentialsProvider(provider); } httpClient = clientBuilder.build(); }
private CredentialsProvider getCredentialsProvider() { CredentialsProvider creds = new BasicCredentialsProvider(); creds.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( model.userNameProperty().get(), model.passwordProperty().get() )); return creds; }
public MarkLogicWriter(final Map<String, String> config){ connectionUrl = config.get(MarkLogicSinkConfig.CONNECTION_URL); user = config.get(MarkLogicSinkConfig.CONNECTION_USER); password = config.get(MarkLogicSinkConfig.CONNECTION_PASSWORD); requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5 * 1000).build(); localContext = HttpClientContext.create(); httpClient = HttpClientBuilder.create().build(); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); localContext.setCredentialsProvider(credentialsProvider); localContext.setRequestConfig(requestConfig); }
/** * Sets the Proxy by it's hostname,port,username and password * * @param hostname the hostname (IP or DNS name) * @param port the port number. -1 indicates the scheme default port. * @param username the username * @param password the password */ public void setProxy(String hostname, int port, String username, String password) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(hostname, port), new UsernamePasswordCredentials(username, password)); final HttpHost proxy = new HttpHost(hostname, port); final HttpParams httpParams = this.httpClient.getParams(); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }
public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) { HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); if (trustSelfSignedCerts) { httpClientBuilder.setSslcontext(buildSslContext()); httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } if (httpProxyConfiguration != null) { HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()); httpClientBuilder.setProxy(proxy); if (httpProxyConfiguration.isAuthRequired()) { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()), new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(), httpProxyConfiguration .getPassword())); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClientBuilder.setRoutePlanner(routePlanner); } HttpClient httpClient = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); return requestFactory; }
/** * * @param uid * @param psw * @return */ @Override public CredentialsProvider setCredentials(String uid, String psw) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(uid, psw)); return credentialsProvider; }
private RestTemplate getRestTemplate ( long maxConnectionInMs, JsonNode user, JsonNode pass, String desc ) { logger.debug( "maxConnectionInMs: {} , user: {} , Pass: {} ", maxConnectionInMs, user, pass ); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); // "user" : "$csapUser1", "pass" : "$csapPass1" if ( user != null && pass != null ) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope( null, -1 ), new UsernamePasswordCredentials( user.asText(), csapApplication.decode( pass.asText(), desc ) ) ); HttpClient httpClient = HttpClients .custom() .setDefaultCredentialsProvider( credsProvider ) .build(); factory.setHttpClient( httpClient ); // factory = new HttpComponentsClientHttpRequestFactory(httpClient); } factory.setConnectTimeout( (int) maxConnectionInMs ); factory.setReadTimeout( (int) maxConnectionInMs ); RestTemplate restTemplate = new RestTemplate( factory ); return restTemplate; }
public static void addSpnego(HttpClientBuilder clientBuilder) { //Add spnego http header processor Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry); //There has to be at least this dummy credentials provider or apache http client gives up BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullCredentials()); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); }
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { final URI uri = URI.create(request.getRequestLine().getUri()); if (uri.getPath().endsWith(loginPath)) { LOG.debug("Request ends with {} so I'm not intercepting the request", loginPath); return; } Cookie loginCookie = getLoginCookie(context, loginTokenName); if (loginCookie != null) { LOG.debug("Request has cookie {}={} so I'm not intercepting the request", loginCookie.getName(), loginCookie.getValue()); return; } // get host final HttpHost host = HttpClientContext.adapt(context).getTargetHost(); // get the username and password from the credentials provider final CredentialsProvider credsProvider = HttpClientContext.adapt(context).getCredentialsProvider(); final AuthScope scope = new AuthScope(host.getHostName(), host.getPort()); final String username = credsProvider.getCredentials(scope).getUserPrincipal().getName(); final String password = credsProvider.getCredentials(scope).getPassword(); List<NameValuePair> parameters = new LinkedList<>(); parameters.add(new BasicNameValuePair("j_username", username)); parameters.add(new BasicNameValuePair("j_password", password)); HttpEntity httpEntity = new UrlEncodedFormEntity(parameters, "utf-8"); HttpPost loginPost = new HttpPost(URI.create(request.getRequestLine().getUri()).resolve(loginPath)); loginPost.setEntity(httpEntity); final CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); client.execute(host, loginPost, context); }
private static ResteasyClient getClient() { // Setting digest credentials CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin"); credentialsProvider.setCredentials(AuthScope.ANY, credentials); HttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, true); // Creating HTTP client return new ResteasyClientBuilder().httpEngine(engine).build(); }