List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:org.picketlink.test.trust.tests.Gateway2ServiceHttpUnitTestCase.java
private String getContentFromApp(String appUri, String userName, String password) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); String content = null;/*from w w w . ja v a2 s. c o m*/ try { httpclient.getCredentialsProvider().setCredentials(new AuthScope(getServerAddress(), 8080), // localhost new UsernamePasswordCredentials(userName, password)); HttpGet httpget = new HttpGet(getTargetURL(appUri)); log.debug("executing request:" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); assertEquals("Http response has to finish with 'HTTP/1.1 200 OK'", 200, response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); log.debug("Status line: " + response.getStatusLine()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.writeTo(baos); content = baos.toString(); baos.close(); if (log.isTraceEnabled()) { log.trace(content); } EntityUtils.consume(entity); } finally { httpclient.getConnectionManager().shutdown(); } return content; }
From source file:pl.psnc.synat.wrdz.zmd.download.adapters.HttpDownloadAdapter.java
@Override public String downloadFile(URI uri, String relativePath) throws DownloadAdapterException { String cachedFilePath = getResourceCachePath(relativePath); checkDestinationExistence(cachedFilePath); DefaultHttpClient httpclient = new DefaultHttpClient(); ReadableByteChannel rbc = null; FileOutputStream output = null; try {// www . j av a2s.co m if (usernamePasswordCredentials != null) { httpclient.getCredentialsProvider().setCredentials(authScope, usernamePasswordCredentials); } HttpResponse response = httpclient.execute(new HttpGet(uri)); HttpEntity entity = response.getEntity(); if (entity != null && response.getStatusLine().getStatusCode() == 200) { rbc = Channels.newChannel(entity.getContent()); output = new FileOutputStream(cachedFilePath); output.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); EntityUtils.consume(entity); } else { EntityUtils.consume(entity); throw new DownloadAdapterException( "Http error code or empty content was returned instead of resource."); } } catch (IOException e) { throw new DownloadAdapterException("Exception caught while downloading file contents to the cache.", e); } finally { httpclient.getConnectionManager().shutdown(); try { if (rbc != null) { rbc.close(); } if (output != null) { output.close(); } } catch (IOException e) { throw new DownloadAdapterException("Exception caught while closing input/output streams.", e); } } return cachedFilePath; }
From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpClientConfigurer.java
private void useCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials, String host, int port) { Credentials basicCredentials = new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword());/* w ww.j a v a 2 s. co m*/ httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), basicCredentials); NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials); Credentials ntCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(), ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain()); httpClient.getCredentialsProvider() .setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthPolicy.NTLM), ntCredentials); LOGGER.debug("Using {} and {} for authenticating against '{}:{}'", new Object[] { credentials, ntlmCredentials, host, port }); }
From source file:com.katsu.springframework.security.authentication.dni.HttpDniAuthenticationDao.java
private Collection<? extends GrantedAuthority> doLogin(URL url, String username, String password, String dni) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = null;/* www.j av a 2 s .co m*/ HttpResponse httpResponse = null; HttpEntity entity = null; try { httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(username, password)); URIBuilder urib = new URIBuilder(url.toURI().toASCIIString()); urib.addParameter("dni", dni); httpget = new HttpGet(urib.build()); httpResponse = httpclient.execute(httpget); entity = httpResponse.getEntity(); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { logger.trace(httpResponse.getStatusLine().toString()); String body = new java.util.Scanner(new InputStreamReader(entity.getContent())).useDelimiter("\\A") .next(); List<? extends GrantedAuthority> roles = json.deserialize(body, new TypeToken<List<Role>>() { }.getType()); if (roles != null && roles.size() > 0 && roles.get(0).getAuthority() == null) { roles = json.deserialize(body, new TypeToken<List<Role1>>() { }.getType()); } return roles; } else { throw new Exception(httpResponse.getStatusLine().getStatusCode() + " Http code response."); } } catch (Exception e) { if (entity != null) { logger.error(log(entity.getContent()), e); } else { logger.error(e); } throw e; } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:com.google.code.maven.plugin.http.client.Proxy.java
/** * prepares the httpclient for using this proxy configuration when opening http connection * //from w w w . ja v a2 s . com * @param httpclient */ public void prepare(DefaultHttpClient httpclient) { HttpHost proxyHost = new HttpHost(host, port); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); if (credentials != null) { httpclient.getCredentialsProvider().setCredentials(// new AuthScope(host, port), // credentials.toUsernamePasswordCredentials()); } }
From source file:makesense.ara.Collector.java
private void connect() { DefaultHttpClient httpclient = new DefaultHttpClient(); try {// www . ja v a 2 s.c om // for the moment, we use AuthScope.ANY and SingleAuth // in the future, think about MultiAuth to allow several accounts httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(data.get("login"), data.get("password"))); HttpGet httpget = new HttpGet(data.get("URL")); HttpResponse httpResponse = httpclient.execute(httpget); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String content; BufferedReader br = new BufferedReader(new InputStreamReader(instream)); // we read as long as we do not ask to stop while (!stop) { content = br.readLine(); if (content != null) { System.out.println(content); } // if } // while } // if } // try catch (IOException ioe) { ioe.printStackTrace(); } // catch finally { httpclient.getConnectionManager().shutdown(); } // finally }
From source file:org.fedoracommons.funapi.pmh.AbstractPmhResolver.java
protected HttpClient getHttpClient() { if (httpClient != null) { return httpClient; }/*w ww . jav a 2 s .c o m*/ SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); HttpParams params = new BasicHttpParams(); // Increase max total connection to 200 params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 200); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, 20); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient httpClient = new DefaultHttpClient(cm, params); if (getUsername() != null && getPassword() != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(getPmhBaseUrl().getHost(), getPmhBaseUrl().getPort()), new UsernamePasswordCredentials(getUsername(), getPassword())); } this.httpClient = httpClient; return httpClient; }
From source file:com.betfair.testing.utils.cougar.manager.HttpPageManager.java
public int getPage(HttpPageBean bean) { // Get bean properties String requestedProtocol = bean.getProtocol(); String requestedHost = bean.getHost(); int requestedPort = bean.getPort(); String requestedLink = bean.getLink(); String username = bean.getAuthusername(); String password = bean.getAuthpassword(); final SSLSocketFactory sf = new SSLSocketFactory(createEasySSLContext(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 9999, sf); // Set up httpClient to use given auth details and protocol DefaultHttpClient client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(https); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); int status = -1; InputStream inputStream = null; // Make the request try {/* ww w.j ava 2 s .c om*/ final HttpGet httpget = new HttpGet( URIUtils.createURI(requestedProtocol, requestedHost, requestedPort, requestedLink, null, null)); final HttpResponse httpResponse = client.execute(httpget); inputStream = httpResponse.getEntity().getContent(); status = httpResponse.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { bean.setPageLoaded(true); byte[] buffer = new byte[(int) httpResponse.getEntity().getContentLength()]; int read; int count = 0; while ((read = inputStream.read()) != -1) { buffer[count] = (byte) read; count++; } bean.setPageText(new String(buffer, "UTF-8")); bean.setBuffer(buffer); } } catch (IOException e1) { return -1; } catch (URISyntaxException e) { return -1; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // ignore } } } return status; }
From source file:org.overlord.dtgov.jbpm.util.HttpClientWorkItemHandler.java
/** * Calls an HTTP endpoint. The address of the endpoint should be set in the * parameter map passed into the workItem by the BPMN workflow. Both * this parameters 'Url' as well as the method 'Method' are required * parameters.//from ww w . j a va2 s . co m */ @Override public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { Governance governance = new Governance(); ClientResponse<?> response = null; Map<String, Object> results = new HashMap<String, Object>(); try { // extract required parameters String urlStr = (String) workItem.getParameter("Url"); //$NON-NLS-1$ String method = (String) workItem.getParameter("Method"); //$NON-NLS-1$ if (urlStr == null || method == null) { throw new Exception(Messages.i18n.format("HttpClientWorkItemHandler.MissingParams")); //$NON-NLS-1$ } urlStr = urlStr.toLowerCase(); urlStr = urlStr.replaceAll("\\{governance.url\\}", governance.getGovernanceUrl()); //$NON-NLS-1$ Map<String, Object> params = workItem.getParameters(); // replace tokens in the urlStr, the replacement value of the token // should be set in the parameters Map for (String key : params.keySet()) { // break out if there are no (more) tokens in the urlStr if (!urlStr.contains("{")) //$NON-NLS-1$ break; // replace the token if it is referenced in the urlStr String variable = "{" + key.toLowerCase() + "}"; //$NON-NLS-1$ //$NON-NLS-2$ if (urlStr.contains(variable)) { String escapedVariable = "\\{" + key.toLowerCase() + "\\}"; //$NON-NLS-1$ //$NON-NLS-2$ String urlEncodedParam = URLEncoder.encode((String) params.get(key), "UTF-8").replaceAll("%2F", //$NON-NLS-1$//$NON-NLS-2$ "*2F"); //$NON-NLS-1$ urlStr = urlStr.replaceAll(escapedVariable, urlEncodedParam); } } if (urlStr.contains("{")) //$NON-NLS-1$ throw new Exception(Messages.i18n.format("HttpClientWorkItemHandler.IncorrectParams", urlStr)); //$NON-NLS-1$ // call http endpoint log.info(Messages.i18n.format("HttpClientWorkItemHandler.CallingTo", method, urlStr)); //$NON-NLS-1$ DefaultHttpClient httpClient = new DefaultHttpClient(); String username = governance.getOverlordUser(); String password = governance.getOverlordPassword(); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); ClientRequest request = new ClientRequest(urlStr, executor); request.setHttpMethod(method); response = request.execute(); int responseCode = response.getResponseStatus().getStatusCode(); if (responseCode >= 200 && responseCode < 300) { Map<String, ValueEntity> map = (Map<String, ValueEntity>) response .getEntity(new GenericType<HashMap<String, ValueEntity>>() { }); for (String key : map.keySet()) { if (map.get(key).getValue() != null) { results.put(key, map.get(key).getValue()); } } log.info("reply=" + results); //$NON-NLS-1$ } else { results.put("Status", "ERROR " + responseCode); //$NON-NLS-1$ //$NON-NLS-2$ results.put("StatusMsg", //$NON-NLS-1$ Messages.i18n.format("HttpClientWorkItemHandler.UnreachableEndpoint", urlStr)); //$NON-NLS-1$ log.error(Messages.i18n.format("HttpClientWorkItemHandler.UnreachableEndpoint", urlStr)); //$NON-NLS-1$ } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (response != null) response.releaseConnection(); } // notify manager that work item has been completed manager.completeWorkItem(workItem.getId(), results); }