List of usage examples for org.apache.http.client CredentialsProvider setCredentials
void setCredentials(AuthScope authscope, Credentials credentials);
From source file:me.willowcheng.makerthings.util.MjpegStreamer.java
public InputStream httpRequest(String url, String usr, String pwd) { HttpResponse res = null;//w w w . j ava 2 s . c om DefaultHttpClient httpclient = new DefaultHttpClient(); CredentialsProvider credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(usr, pwd)); httpclient.setCredentialsProvider(credProvider); Log.d(TAG, "1. Sending http request"); try { res = httpclient.execute(new HttpGet(URI.create(url))); Log.d(TAG, "2. Request finished, status = " + res.getStatusLine().getStatusCode()); if (res.getStatusLine().getStatusCode() == 401) { //You must turn off camera User Access Control before this will work return null; } Log.d(TAG, "content-type = " + res.getEntity().getContentType()); Log.d(TAG, "content-encoding = " + res.getEntity().getContentEncoding()); return res.getEntity().getContent(); } catch (ClientProtocolException e) { e.printStackTrace(); Log.d(TAG, "Request failed-ClientProtocolException", e); //Error connecting to camera } catch (IOException e) { e.printStackTrace(); Log.d(TAG, "Request failed-IOException", e); //Error connecting to camera } return null; }
From source file:nu.yona.server.sms.PlivoSmsService.java
private HttpClientContext createHttpClientContext() { try {/*from w ww. j ava 2s . c om*/ SmsProperties smsProperties = yonaProperties.getSms(); URI uri = getPlivoUrl(smsProperties); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(smsProperties.getPlivoAuthId(), smsProperties.getPlivoAuthToken())); HttpClientContext httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(credentialsProvider); return httpClientContext; } catch (URISyntaxException e) { throw SmsException.smsSendingFailed(e); } }
From source file:com.jwm123.loggly.reporter.Client.java
public List<Map<String, Object>> getReport() throws Exception { final Integer rows = 500; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(config.getAccount() + ".loggly.com", 80), new UsernamePasswordCredentials(config.getUsername(), config.getPassword())); CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); String url = "http://" + config.getAccount() + ".loggly.com/api/search?rows=" + rows + "&q=" + URLEncoder.encode(query, "UTF8"); if (StringUtils.isNotBlank(from)) { url += "&from=" + URLEncoder.encode(from, "UTF8"); }/*from ww w . ja v a 2 s . c om*/ if (StringUtils.isNotBlank(to)) { url += "&until=" + URLEncoder.encode(to, "UTF8"); } HttpGet get = new HttpGet(url); CloseableHttpResponse resp = null; List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); Integer offset = 0 - rows; Integer numFound = 0; try { do { offset += rows; try { get = new HttpGet(url + "&start=" + offset); resp = client.execute(get); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String response = EntityUtils.toString(resp.getEntity()); Map<String, Object> responseMap = new Gson().fromJson(response, new TypeToken<Map<String, Object>>() { }.getType()); if (responseMap.containsKey("numFound")) { numFound = ((Number) responseMap.get("numFound")).intValue(); } if (responseMap.containsKey("data")) { Collection<?> dataCol = (Collection<?>) responseMap.get("data"); if (!dataCol.isEmpty()) { for (Object dataItem : dataCol) { if (dataItem instanceof Map) { results.add((Map<String, Object>) dataItem); } } } } } else { System.out.println("status: " + resp.getStatusLine().getStatusCode() + " Response: [" + EntityUtils.toString(resp.getEntity()) + "]"); break; } } finally { get.releaseConnection(); IOUtils.closeQuietly(resp); } } while (numFound >= offset + rows); } finally { IOUtils.closeQuietly(client); } return results; }
From source file:org.springframework.cloud.dataflow.rest.util.HttpClientConfigurer.java
/** * Configures the {@link HttpClientBuilder} with a proxy host. If the * {@code proxyUsername} and {@code proxyPassword} are not {@code null} * then a {@link CredentialsProvider} is also configured for the proxy host. * * @param proxyUri Must not be null and must be configured with a scheme (http or https). * @param proxyUsername May be null//w w w . j a va 2 s.co m * @param proxyPassword May be null * @return a reference to {@code this} to enable chained method invocation */ public HttpClientConfigurer withProxyCredentials(URI proxyUri, String proxyUsername, String proxyPassword) { Assert.notNull(proxyUri, "The proxyUri must not be null."); Assert.hasText(proxyUri.getScheme(), "The scheme component of the proxyUri must not be empty."); httpClientBuilder.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme())); if (proxyUsername != null && proxyPassword != null) { final CredentialsProvider credentialsProvider = this.getOrInitializeCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider) .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } return this; }
From source file:com.sulacosoft.bitcoindconnector4j.BitcoindApiHandler.java
public BitcoindApiHandler(String host, int port, String protocol, String uri, String username, String password) {//from w ww . j a v a 2 s . co m this.uri = uri; httpClient = HttpClients.createDefault(); targetHost = new HttpHost(host, port, protocol); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); }
From source file:com.quartzdesk.executor.core.job.UrlInvokerJob.java
@Override protected void executeJob(final JobExecutionContext context) throws JobExecutionException { log.debug("Inside job: {}", context.getJobDetail().getKey()); JobDataMap jobDataMap = context.getMergedJobDataMap(); // url (required) final String url = jobDataMap.getString(JDM_KEY_URL); if (url == null) { throw new JobExecutionException("Missing required '" + JDM_KEY_URL + "' job data map parameter."); }//from w w w . ja v a 2 s . c o m // username (optional) String username = jobDataMap.getString(JDM_KEY_USERNAME); // password (optional) String password = jobDataMap.getString(JDM_KEY_PASSWORD); CloseableHttpClient httpClient; if (username != null && password != null) { // use HTTP basic authentication CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); } else { // use no HTTP authentication httpClient = HttpClients.custom().build(); } try { HttpPost httpPost = new HttpPost(url); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse httpResponse) throws IOException { int status = httpResponse.getStatusLine().getStatusCode(); //context.setResult( Integer.toString( status ) ); if (status >= 200 && status < 300) { HttpEntity entity = httpResponse.getEntity(); return entity == null ? null : EntityUtils.toString(entity); } else { throw new ClientProtocolException( "URL: " + url + " returned unexpected response status code: " + status); } } }; log.debug("HTTP request line: {}", httpPost.getRequestLine()); log.info("Invoking target URL: {}", url); String responseText = httpClient.execute(httpPost, responseHandler); log.debug("Response text: {}", responseText); if (!responseText.trim().isEmpty()) { /* * We use the HTTP response text as the Quartz job execution result. This code can then be easily * viewed in the Execution History in the QuartzDesk GUI and it can be, for example, used to trigger * execution notifications. */ context.setResult(responseText); } } catch (IOException e) { throw new JobExecutionException("Error invoking URL: " + url, e); } finally { try { httpClient.close(); } catch (IOException e) { log.error("Error closing HTTP client.", e); } } }
From source file:com.bosch.cr.integration.helloworld.ProxyServlet.java
/** * Create http client/*w w w. jav a 2s . c om*/ */ private synchronized CloseableHttpClient getHttpClient() { if (httpClient == null) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (props.getProperty("http.proxyHost") != null) { httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"), Integer.parseInt(props.getProperty("http.proxyPort")))); } if (props.getProperty("http.proxyUser") != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials( props.getProperty("http.proxyUser"), props.getProperty("http.proxyPwd"))); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } httpClient = httpClientBuilder.build(); } return httpClient; }
From source file:org.thingsboard.server.dao.audit.sink.ElasticsearchAuditLogSink.java
@PostConstruct public void init() { try {//from w w w .ja va 2s. c o m log.trace("Adding elastic rest endpoint... host [{}], port [{}], scheme name [{}]", host, port, schemeName); RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, schemeName)); if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)) { log.trace("...using username [{}] and password ***", userName); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); builder.setHttpClientConfigCallback( httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)); } this.restClient = builder.build(); } catch (Exception e) { log.error("Sink init failed!", e); throw new RuntimeException(e.getMessage(), e); } }
From source file:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java
/** * @return Provider of credentials for preemptive auth *//*ww w. j a v a2 s . c o m*/ protected CredentialsProvider credentialsProvider() { String hostname = nexusUrl.getHost(); AuthScope scope = new AuthScope(hostname, -1); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(scope, credentials()); return credentialsProvider; }