List of usage examples for org.apache.http.client CredentialsProvider setCredentials
void setCredentials(AuthScope authscope, Credentials credentials);
From source file:org.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java
/** * Http Post Request./* w w w.j a v a2 s. c om*/ * @param url Target URL to POST to. * @param body Body to be sent with the post. * @param credentials Credentials to use for basic auth. * @return Body of post returned. * @throws Exception */ private static String httpPost(String url, String body, UsernamePasswordCredentials credentials) throws Exception { CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, credentials); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); HttpPost httpPost = new HttpPost(url); AuthCache authCache = new BasicAuthCache(); HttpHost targetHost = new HttpHost(httpPost.getURI().getHost(), httpPost.getURI().getPort()); authCache.put(targetHost, new BasicScheme()); final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(provider); context.setAuthCache(authCache); httpPost.setEntity(new StringEntity(body)); HttpResponse response = client.execute(httpPost, context); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); String responseBody = entity != null ? EntityUtils.toString(entity) : null; if (status >= 400) { Exception e = new Exception(String.format( "POST request to %s failed with status code: %d. Response: %s", url, status, responseBody)); logger.error(e.getMessage()); throw e; } logger.debug("Status: " + status); return responseBody; }
From source file:aajavafx.EmployeeController.java
public static void validate(Employees emp) { try {//from ww w . j a va 2s .c o m Gson gson = new Gson(); String jsonString = new String(gson.toJson(emp)); System.out.println("json string: " + jsonString); StringEntity postString = new StringEntity(jsonString); CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password"); provider.setCredentials(AuthScope.ANY, credentials); HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); HttpPost post = new HttpPost(postEmployeesURL); post.setEntity(postString); post.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(post); } catch (UnsupportedEncodingException ex) { System.out.println(ex); } catch (IOException e) { System.out.println(e); } }
From source file:eu.diacron.crawlservice.app.Util.java
public static void getAllCrawls() { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME, Configuration.REMOTE_CRAWLER_PASS)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {//from w ww . ja v a 2s . com //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl"); HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); System.out.println(response.getEntity().getContent()); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:eu.diacron.crawlservice.app.Util.java
public static String getCrawlid(URL urltoCrawl) { String crawlid = ""; System.out.println("start crawling page"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME, Configuration.REMOTE_CRAWLER_PASS)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {/*w ww . j a v a2 s .c o m*/ //HttpPost httppost = new HttpPost("http://diachron.hanzoarchives.com/crawl"); HttpPost httppost = new HttpPost(Configuration.REMOTE_CRAWLER_URL_CRAWL_INIT); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("name", UUID.randomUUID().toString())); urlParameters.add(new BasicNameValuePair("scope", "page")); urlParameters.add(new BasicNameValuePair("seed", urltoCrawl.toString())); httppost.setEntity(new UrlEncodedFormEntity(urlParameters)); System.out.println("Executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { crawlid = inputLine; } in.close(); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } return crawlid; }
From source file:eu.diacron.crawlservice.app.Util.java
public static String getCrawlStatusById(String crawlid) { String status = ""; System.out.println("get crawlid"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME, Configuration.REMOTE_CRAWLER_PASS)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {//from www. j a va 2 s . c o m //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl/" + crawlid); HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL + crawlid); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); String result = ""; BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); result += inputLine; } in.close(); // TO-DO should be removed in the future and handle it more gracefully result = result.replace("u'", "'"); result = result.replace("'", "\""); JSONObject crawljson = new JSONObject(result); System.out.println("myObject " + crawljson.toString()); status = crawljson.getString("status"); EntityUtils.consume(response.getEntity()); } catch (JSONException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { response.close(); } } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } return status; }
From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java
public static void setNTCredentials(HttpClientBuilder builder, String username, String password, String workStation, String domain) { // set Username and Password if (!StringUtil.isEmpty(username, true)) { if (password == null) password = ""; CredentialsProvider cp = new BasicCredentialsProvider(); builder.setDefaultCredentialsProvider(cp); cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(username, password, workStation, domain)); }/*from www . ja v a 2 s . com*/ }
From source file:com.oakesville.mythling.util.HttpHelper.java
public static HttpContext getDigestAuthContext(String host, int port, String user, String password) { CredentialsProvider cp = new BasicCredentialsProvider(); AuthScope scope = new AuthScope(host, port); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); cp.setCredentials(scope, creds); HttpContext credContext = new BasicHttpContext(); credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp); return credContext; }
From source file:com.moviejukebox.tools.YamjHttpClientBuilder.java
@SuppressWarnings("resource") private static YamjHttpClient buildHttpClient() { LOG.trace("Create new YAMJ http client"); // create proxy HttpHost proxy = null;/* www. j a va2s. c o m*/ CredentialsProvider credentialsProvider = null; if (StringUtils.isNotBlank(PROXY_HOST) && PROXY_PORT > 0) { proxy = new HttpHost(PROXY_HOST, PROXY_PORT); if (StringUtils.isNotBlank(PROXY_USERNAME) && StringUtils.isNotBlank(PROXY_PASSWORD)) { credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT), new UsernamePasswordCredentials(PROXY_USERNAME, PROXY_PASSWORD)); } } PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(TIMEOUT_SOCKET).build()); connManager.setMaxTotal(20); connManager.setDefaultMaxPerRoute(2); CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(1000).setMaxObjectSize(8192).build(); HttpClientBuilder builder = CachingHttpClientBuilder.create().setCacheConfig(cacheConfig) .setConnectionManager(connManager).setProxy(proxy) .setDefaultCredentialsProvider(credentialsProvider) .setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_READ) .setConnectTimeout(TIMEOUT_CONNECT).setSocketTimeout(TIMEOUT_SOCKET) .setCookieSpec(CookieSpecs.IGNORE_COOKIES).setProxy(proxy).build()); // show status showStatus(); // build the client YamjHttpClient wrapper = new YamjHttpClient(builder.build(), connManager); wrapper.setUserAgentSelector(new WebBrowserUserAgentSelector()); wrapper.addGroupLimit(".*", 1); // default limit, can be overwritten // First we have to read/create the rules String maxDownloadSlots = PropertiesUtil.getProperty("mjb.MaxDownloadSlots"); if (StringUtils.isNotBlank(maxDownloadSlots)) { LOG.debug("Using download limits: {}", maxDownloadSlots); Pattern pattern = Pattern.compile(",?\\s*([^=]+)=(\\d+)"); Matcher matcher = pattern.matcher(maxDownloadSlots); while (matcher.find()) { String group = matcher.group(1); try { final Integer maxResults = Integer.valueOf(matcher.group(2)); wrapper.addGroupLimit(group, maxResults); LOG.trace("Added download slot '{}' with max results {}", group, maxResults); } catch (NumberFormatException error) { LOG.debug("Rule '{}' is no valid regexp, ignored", group); } } } return wrapper; }
From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java
public static BasicHttpContext setCredentials(HttpClientBuilder builder, HttpHost httpHost, String username, String password, boolean preAuth) { // set Username and Password if (!StringUtil.isEmpty(username, true)) { if (password == null) password = ""; CredentialsProvider cp = new BasicCredentialsProvider(); builder.setDefaultCredentialsProvider(cp); cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); BasicHttpContext httpContext = new BasicHttpContext(); if (preAuth) { AuthCache authCache = new BasicAuthCache(); authCache.put(httpHost, new BasicScheme()); httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }/*from w w w. j a v a 2s .co m*/ return httpContext; } return null; }
From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java
public static void setProxy(HttpClientBuilder builder, HttpUriRequest request, ProxyData proxy) { // set Proxy/* w ww . j a va2 s .c o m*/ if (ProxyDataImpl.isValid(proxy)) { HttpHost host = new HttpHost(proxy.getServer(), proxy.getPort() == -1 ? 80 : proxy.getPort()); builder.setProxy(host); // username/password if (!StringUtil.isEmpty(proxy.getUsername())) { CredentialsProvider cp = new BasicCredentialsProvider(); builder.setDefaultCredentialsProvider(cp); cp.setCredentials(new AuthScope(proxy.getServer(), proxy.getPort()), new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword())); } } }