List of usage examples for org.apache.http.auth AuthScope AuthScope
public AuthScope(final String host, final int port)
From source file:li.klass.fhem.fhem.FHEMWEBConnection.java
private RequestResult<InputStream> executeRequest(String urlSuffix, DefaultHttpClient client, String command) { String url = null;/* w ww .j a v a 2s. c om*/ if (client == null) { client = createNewHTTPClient(getConnectionTimeoutMilliSeconds(), SOCKET_TIMEOUT); } try { HttpGet request = new HttpGet(); request.addHeader("Accept-Encoding", "gzip"); url = serverSpec.getUrl() + urlSuffix; Log.i(TAG, "accessing URL " + url); URI uri = new URI(url); client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(serverSpec.getUsername(), getPassword())); request.setURI(uri); HttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); Log.d(TAG, "response status code is " + statusCode); RequestResult<InputStream> errorResult = handleHttpStatusCode(statusCode); if (errorResult != null) { String msg = "found error " + errorResult.error.getClass().getSimpleName() + " for " + "status code " + statusCode; Log.d(TAG, msg); ErrorHolder.setError(null, msg); return errorResult; } InputStream contentStream = response.getEntity().getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { contentStream = new GZIPInputStream(contentStream); } return new RequestResult<InputStream>(contentStream); } catch (ConnectTimeoutException e) { Log.i(TAG, "connection timed out", e); setErrorInErrorHolderFor(e, url, command); return new RequestResult<InputStream>(RequestResultError.CONNECTION_TIMEOUT); } catch (ClientProtocolException e) { String errorText = "cannot connect, invalid URL? (" + url + ")"; setErrorInErrorHolderFor(e, url, command); ErrorHolder.setError(e, errorText); return new RequestResult<InputStream>(RequestResultError.HOST_CONNECTION_ERROR); } catch (IOException e) { Log.i(TAG, "cannot connect to host", e); setErrorInErrorHolderFor(e, url, command); return new RequestResult<InputStream>(RequestResultError.HOST_CONNECTION_ERROR); } catch (URISyntaxException e) { Log.i(TAG, "invalid URL syntax", e); setErrorInErrorHolderFor(e, url, command); throw new IllegalStateException("cannot parse URL " + urlSuffix, e); } }
From source file:org.mariotaku.twidere.util.net.HttpClientImpl.java
public HttpClientImpl(final HttpClientConfiguration conf) { this.conf = conf; final SchemeRegistry registry = new SchemeRegistry(); final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY : SSLSocketFactory.getSocketFactory(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", factory, 443)); final HttpParams params = new BasicHttpParams(); final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry); final DefaultHttpClient client = new DefaultHttpClient(cm, params); final HttpParams clientParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(clientParams, conf.getHttpConnectionTimeout()); HttpConnectionParams.setSoTimeout(clientParams, conf.getHttpReadTimeout()); if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) { final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) { if (logger.isDebugEnabled()) { logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser()); logger.debug(/*from w w w.j a va 2 s . co m*/ "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword())); } client.getCredentialsProvider().setCredentials( new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()), new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword())); } } this.client = client; }
From source file:org.springframework.cloud.dataflow.rest.util.HttpClientConfigurerTests.java
/** * Test ensuring that the {@link AuthScope} is set for the target host and the proxy server. *//* w w w . ja va 2 s. co m*/ @Test public void testThatHttpClientWithProxyIsCreatedAndHasCorrectCredentialsProviders2() throws Exception { final URI targetHost = new URI("http://test.com"); final HttpClientConfigurer builder = HttpClientConfigurer.create(targetHost); builder.basicAuthCredentials("foo", "password"); builder.withProxyCredentials(URI.create("https://spring.io"), "proxyuser", "proxypassword"); final Field credentialsProviderField = ReflectionUtils.findField(HttpClientConfigurer.class, "credentialsProvider"); ReflectionUtils.makeAccessible(credentialsProviderField); CredentialsProvider credentialsProvider = (CredentialsProvider) credentialsProviderField.get(builder); Assert.assertNotNull(credentialsProvider.getCredentials(new AuthScope("test.com", 80))); Assert.assertNotNull(credentialsProvider.getCredentials(new AuthScope("spring.io", 80))); }
From source file:org.sbs.goodcrawler.fetcher.Fetcher.java
public void init(File fetchConfFile) { FetchConfig fetchConfig = new FetchConfig(); Document document;// w ww . jav a 2 s . c o m try { document = Jsoup.parse(fetchConfFile, "utf-8"); Fetcher.config = fetchConfig.loadConfig(document); } catch (IOException e) { e.printStackTrace(); } catch (ConfigurationException e) { e.printStackTrace(); } HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); paramsBean.setUseExpectContinue(false); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(CoreProtocolPNames.USER_AGENT, config.getAgent()); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeoutMilliseconds()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); params.setBooleanParameter("http.protocol.handle-redirects", false); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); if (config.isHttps()) { schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); } connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); httpClient = new DefaultHttpClient(connectionManager, params); if (config.getProxyHost() != null) { if (config.getProxyUsername() != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); } HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null) { HeaderElement[] codecs = contentEncoding.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); if (connectionMonitorThread == null) { connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager); } connectionMonitorThread.start(); }
From source file:com.sampleapp.db.CloudantDAOFactory.java
public CloudantDAOFactory(Properties serviceProperties) { if (serviceProperties == null) { System.out.println("No VCAP_SERVICES found"); return;// w w w . j a v a2s. c o m } System.out.println("VCAP_SERVICES found"); try { // Grab Cloudant credentials from VCAP_SERVICES url = serviceProperties.getProperty("url"); username = serviceProperties.getProperty("username"); password = serviceProperties.getProperty("password"); database = serviceProperties.getProperty("database"); System.out.println("Found all the params"); // Setting up to access Cloudant db credsProvider.setCredentials(new AuthScope(username + ".cloudant.com", 443), new UsernamePasswordCredentials(username, password)); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); System.out.println("Using Cloudant DB at url " + url + "/" + database); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.seyren.core.service.checker.GraphiteTargetChecker.java
/** * Set auth header for graphite if username and password are provided *//*from w w w.java 2 s . c o m*/ private void setAuthHeadersIfNecessary() { if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(graphiteHost, AuthScope.ANY_PORT), new UsernamePasswordCredentials(graphiteUsername, graphitePassword)); if (client instanceof AbstractHttpClient) { ((AbstractHttpClient) client).setCredentialsProvider(credsProvider); } } }
From source file:org.zenoss.app.consumer.metric.impl.MetricServicePoster.java
/** * Login to the ZAuth service using the zenoss credentials. Grab the tenant id from the http response and cache * the results for future requests./*from ww w . j a va2s. c om*/ * @return tenant id * @throws IOException */ String getTenantId() throws IOException { if (tenantId == null) { log.debug("Requesting tenant id"); // get the hostname and port from ProxyConfiguration ProxyConfiguration proxyConfig = configuration.getProxyConfiguration(); String hostname = proxyConfig.getHostname(); int port = proxyConfig.getPort(); //configure request HttpContext context = new BasicHttpContext(); HttpHost host = new HttpHost(hostname, port, "http"); HttpPost post = new HttpPost(AUTHENTICATE_URL); post.addHeader(ACCEPT, APPLICATION_JSON.toString()); //configure authentication String username = configuration.getZenossCredentials().getUsername(); String password = configuration.getZenossCredentials().getPassword(); if (!Strings.nullToEmpty(username).isEmpty()) { //configure credentials CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(username, password)); context.setAttribute(ClientContext.CREDS_PROVIDER, provider); //setup auth cache AuthCache cache = new BasicAuthCache(); BasicScheme scheme = new BasicScheme(); cache.put(host, scheme); context.setAttribute(ClientContext.AUTH_CACHE, cache); } //handle response and collect tenantId HttpResponse response = null; try { response = httpClient.execute(host, post, context); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); log.debug("Tenant id request complete with status: {}", statusCode); if (statusCode >= 200 && statusCode <= 299) { Header id = response.getFirstHeader(ZenossTenant.ID_HTTP_HEADER); if (id == null) { log.warn("Failed to get zauth tenant id after login"); throw new RuntimeException("Failed to get zauth tenant id after successful login"); } tenantId = id.getValue(); log.info("Got tenant id: {}", tenantId); } else { log.warn("Unsuccessful response from server: {}", response.getStatusLine()); throw new IOException("Login for tenantId failed"); } } catch (NullPointerException ex) { log.warn("npe retrieving tenantId: {}", ex); } finally { try { if (response != null) { response.getEntity().getContent().close(); } } catch (NullPointerException | IOException ex) { log.warn("Failed to close request: {}", ex); } } } return tenantId; }
From source file:com.cheddargetter.client.service.CheddarGetterPaymentService.java
public void afterPropertiesSet() throws Exception { context = newInstance(Customers.class, Plans.class, Error.class, Success.class); ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(); connManager.setMaxTotal(25);//from w ww.j ava 2 s .co m DefaultHttpClient httpClient = new DefaultHttpClient(connManager); httpClient.getCredentialsProvider().setCredentials( new AuthScope(getHost().getHostName(), getHost().getPort()), new UsernamePasswordCredentials(getUserName(), getPassword())); this.httpClient = httpClient; }
From source file:com.dwdesign.tweetings.util.httpclient.HttpClientImpl.java
public HttpClientImpl(final HttpClientConfiguration conf) { this.conf = conf; final SchemeRegistry registry = new SchemeRegistry(); //final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY : SSLSocketFactory // .getSocketFactory(); final SSLSocketFactory factory = TRUST_ALL_SSL_SOCKET_FACTORY; registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", factory, 443)); final HttpParams params = new BasicHttpParams(); final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry); final DefaultHttpClient client = new DefaultHttpClient(cm, params); final HttpParams client_params = client.getParams(); HttpConnectionParams.setConnectionTimeout(client_params, conf.getHttpConnectionTimeout()); HttpConnectionParams.setSoTimeout(client_params, conf.getHttpReadTimeout()); if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) { final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) { if (logger.isDebugEnabled()) { logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser()); logger.debug("Proxy AuthPassword: " + z_T4JInternalStringUtil.maskString(conf.getHttpProxyPassword())); }/*from ww w.j a v a 2 s .c o m*/ client.getCredentialsProvider().setCredentials( new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()), new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword())); } } this.client = client; }