List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme
public BasicScheme()
From source file:net.homelinux.penecoptero.android.citybikes.app.RESTHelper.java
private DefaultHttpClient setCredentials(DefaultHttpClient httpclient, String url) throws HttpException, IOException { HttpHost targetHost = new HttpHost(url); final UsernamePasswordCredentials access = new UsernamePasswordCredentials(USERNAME, PASSWORD); httpclient.getCredentialsProvider()//from w w w . j a v a 2 s .c om .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), access); httpclient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() == null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(access); } } }, 0); return httpclient; }
From source file:ua.pp.msk.maven.MavenHttpClient.java
private int execute(File file) throws ArtifactPromotingException { CloseableHttpClient client = HttpClientBuilder.create().build(); int status = -1; try {/* w w w. j a v a 2s . c o m*/ getLog().debug("Connecting to URL: " + url); HttpPost post = new HttpPost(url); post.setHeader("User-Agent", userAgent); if (username != null && username.length() != 0 && password != null) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); post.addHeader(new BasicScheme().authenticate(creds, post, null)); } if (file == null) { if (!urlParams.isEmpty()) { post.setEntity(new UrlEncodedFormEntity(urlParams)); } } else { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (!urlParams.isEmpty()) { for (NameValuePair nvp : urlParams) { builder.addPart(nvp.getName(), new StringBody(nvp.getValue(), ContentType.MULTIPART_FORM_DATA)); } } FileBody fb = new FileBody(file); // Not used because of form submission // builder.addBinaryBody("file", file, // ContentType.DEFAULT_BINARY, file.getName()); builder.addPart("file", fb); HttpEntity sendEntity = builder.build(); post.setEntity(sendEntity); } CloseableHttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); status = statusLine.getStatusCode(); getLog().info( "Response status code: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); // Perhaps I need to parse html // String html = EntityUtils.toString(entity); } catch (AuthenticationException ex) { throw new ArtifactPromotingException(ex); } catch (UnsupportedEncodingException ex) { throw new ArtifactPromotingException(ex); } catch (IOException ex) { throw new ArtifactPromotingException(ex); } finally { try { client.close(); } catch (IOException ex) { throw new ArtifactPromotingException("Cannot close http client", ex); } } return status; }
From source file:de.escidoc.core.test.common.fedora.TripleStoreTestBase.java
/** * Request SPO query to MPT triple store. * * @param spoQuery The SPO query./*from w ww . j a va2 s . com*/ * @param outputFormat The triple store output format (N-Triples/RDF/XML/Turtle/..) * @return query result * @throws Exception If anything fails. */ public String requestMPT(final String spoQuery, final String outputFormat) throws Exception { HttpPost post = new HttpPost(getFedoraUrl() + "/risearch"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("format", outputFormat)); formparams.add(new BasicNameValuePair("query", spoQuery)); formparams.add(new BasicNameValuePair("type", TYPE_MPT)); formparams.add(new BasicNameValuePair("lang", LANG_MPT)); // The flush parameter tells the resource index to ensure // that any recently-added/modified/deleted triples are // flushed to the triplestore before executing the query. formparams.add(new BasicNameValuePair("flush", FLUSH)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, HTTP.UTF_8); post.setEntity(entity); int resultCode = 0; try { DefaultHttpClient httpClient = getHttpClient(); BasicHttpContext localcontext = new BasicHttpContext(); BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0); HttpResponse httpRes = httpClient.execute(post, localcontext); if (httpRes.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { throw new Exception("Bad request. Http response : " + resultCode); } String result = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8); if (result == null) { return null; } if (result.startsWith("<html")) { Pattern p = Pattern.compile(QUERY_ERROR); Matcher m = p.matcher(result); Pattern p1 = Pattern.compile(PARSE_ERROR); Matcher m1 = p1.matcher(result); Pattern p2 = Pattern.compile(FORMAT_ERROR); Matcher m2 = p2.matcher(result); if (m.find()) { result = Constants.CDATA_START + result + Constants.CDATA_END; if (m1.find()) { throw new Exception(result); } else if (m2.find()) { throw new Exception(result); } } else { result = Constants.CDATA_START + result + Constants.CDATA_END; throw new Exception("Request to MPT failed." + result); } } return result; } catch (final Exception e) { throw new Exception(e.toString(), e); } }
From source file:com.controlj.experiment.bulktrend.trendclient.TrendClient.java
public void go() { DefaultHttpClient client = null;//w w w . j av a 2 s . c o m try { prepareForResponse(); if (altInput == null) { client = new DefaultHttpClient(); // Set up preemptive Basic Authentication UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); BasicHttpContext localcontext = new BasicHttpContext(); BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0); if (zip) { client.addRequestInterceptor(new GZipRequestInterceptor()); client.addResponseInterceptor(new GZipResponseInterceptor()); } HttpPost post = new HttpPost(url); try { setPostData(post); HttpResponse response = client.execute(post, localcontext); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.println( "Error: Web Service response code of: " + response.getStatusLine().getStatusCode()); return; } HttpEntity entity = response.getEntity(); if (entity != null) { parser.parseResponse(ids.size(), entity.getContent()); } } catch (IOException e) { System.err.println("IO Error reading response"); e.printStackTrace(); } } else { // Alternate input (typically from a file) for testing try { parser.parseResponse(ids.size(), altInput); } catch (IOException e) { System.err.println("IO Error reading response"); e.printStackTrace(); } } } finally { if (client != null) { client.getConnectionManager().shutdown(); } } /* try { parser.parseResponse(ids.size(), new FileInputStream(new File("response.dump"))); } catch (IOException e) { e.printStackTrace(); } */ }
From source file:org.artificer.test.AbstractIntegrationTest.java
protected ClientRequest clientRequest(String endpoint) { DefaultHttpClient client = new DefaultHttpClient(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD); client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost targetHost = new HttpHost(HOST, PORT); authCache.put(targetHost, basicAuth); BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext); ClientRequest clientRequest = new ClientRequest(BASE_URL + endpoint, executor); return clientRequest; }
From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpClientConfigurer.java
public void configureMethod(HttpRequest method) { method.addHeader("User-Agent", "Gradle/" + GradleVersion.current().getVersion()); // Do preemptive authentication for basic auth if (repositoryCredentials != null) { try {/*from ww w . ja va 2 s . c o m*/ method.addHeader(new BasicScheme().authenticate(repositoryCredentials, method)); } catch (AuthenticationException e) { throw UncheckedException.throwAsUncheckedException(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);/* w ww. j av a2 s . c o m*/ return context; }
From source file:majordodo.client.http.HTTPClientConnection.java
private HttpClientContext getContext() throws IOException { if (context == null) { BrokerAddress broker = getBroker(); String scheme = broker.getProtocol(); HttpHost targetHost = new HttpHost(broker.getAddress(), broker.getPort(), scheme); context = HttpClientContext.create(); if (configuration.getUsername() != null && !configuration.getUsername().isEmpty()) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME), creds); BasicAuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); }//www . j a va2 s. co m } return context; }
From source file:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient4Connector.java
/** * Method to create the {@link HttpClient} * /*from w ww . ja va 2 s . c o m*/ * @return the {@link DefaultHttpClient} */ private DefaultHttpClient createClient() { DefaultHttpClient client = new DefaultHttpClient(); if (server.isSecured()) { log.debug("The Server is secured, create the BasicHttpContext to handle preemptive authentication."); client.getCredentialsProvider().setCredentials(getAuthScope(), new UsernamePasswordCredentials(server.getUsername(), server.getPassword())); localContext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local execution context BasicScheme basicAuth = new BasicScheme(); localContext.setAttribute("preemptive-auth", basicAuth); // Add as the first request intercepter client.addRequestInterceptor(new PreemptiveAuth(), 0); } if (StringUtils.isNotBlank(System.getProperty("http.proxyHost")) || StringUtils.isNotBlank(System.getProperty("https.proxyHost"))) { log.debug("A System HTTP(S) proxy is set, set the ProxySelectorRoutePlanner for the client"); System.setProperty("java.net.useSystemProxies", "true"); // Set the ProxySelectorRoute Planner to automatically select the system proxy host if set. client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault())); } return client; }
From source file:org.xwiki.eclipse.storage.rest.XWikiRestClient.java
protected HttpResponse executeGet(URI uri) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); HttpGet request = new HttpGet(uri); request.addHeader(new BasicScheme().authenticate(creds, request)); HttpResponse response = httpClient.execute(request); return response; }