List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:org.keycloak.testsuite.federation.AbstractKerberosTest.java
protected void initHttpClient(boolean useSpnego) { if (client != null) { after();//w w w .j av a 2 s . com } DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder().build(); httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, spnegoSchemeFactory); if (useSpnego) { Credentials fake = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), fake); } ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); client = new ResteasyClientBuilder().httpEngine(engine).build(); }
From source file:org.rhq.modules.plugins.wildfly10.ASUploadConnection.java
/** * Triggers the real upload to the AS7 instance. At this point the caller should have written * the content in the {@link OutputStream} given by {@link #getOutputStream()}. * //from w w w . ja va2s . co m * @return a {@link JsonNode} instance read from the upload response body or null if something went wrong. */ public JsonNode finishUpload() { if (filename == null) { // At this point the fileName should have been set whether at instanciation or in #getOutputStream(String) throw new IllegalStateException("Upload fileName is null"); } closeQuietly(cacheOutputStream); SchemeRegistry schemeRegistry = new SchemeRegistryBuilder(asConnectionParams).buildSchemeRegistry(); ClientConnectionManager httpConnectionManager = new BasicClientConnectionManager(schemeRegistry); DefaultHttpClient httpClient = new DefaultHttpClient(httpConnectionManager); HttpParams httpParams = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, timeout); if (credentials != null && !asConnectionParams.isClientcertAuthentication()) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(asConnectionParams.getHost(), asConnectionParams.getPort()), credentials); // If credentials were provided, we will first send a GET request to trigger the authentication challenge // This allows to send the potentially big file only once to the server // The typical resulting http exchange would be: // // GET without auth <- 401 (start auth challenge : the server will name the realm and the scheme) // GET with auth <- 200 // POST big file // // Note this only works because we use SimpleHttpConnectionManager which maintains only one HttpConnection // // A better way to avoid uploading a big file twice would be to use the header "Expect: Continue" // Unfortunately AS7 replies "100 Continue" even if authentication headers are not present yet // // There is no need to trigger digest authentication when client certification authentication is used HttpGet triggerAuthRequest = new HttpGet(triggerAuthUri); try { // Send GET request in order to trigger authentication // We don't check response code because we're not already uploading the file httpClient.execute(triggerAuthRequest); } catch (Exception ignore) { // We don't stop trying upload if triggerAuthRequest raises exception // See comment above } finally { triggerAuthRequest.abort(); } } String uploadURL = (asConnectionParams.isSecure() ? ASConnection.HTTPS_SCHEME : ASConnection.HTTP_SCHEME) + "://" + asConnectionParams.getHost() + ":" + asConnectionParams.getPort() + UPLOAD_URI; HttpPost uploadRequest = new HttpPost(uploadUri); try { // Now upload file with multipart POST request MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart(filename, new FileBody(cacheFile)); uploadRequest.setEntity(multipartEntity); HttpResponse uploadResponse = httpClient.execute(uploadRequest); if (uploadResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logUploadDoesNotEndWithHttpOkStatus(uploadResponse); return null; } ObjectMapper objectMapper = new ObjectMapper(); InputStream responseBodyAsStream = uploadResponse.getEntity().getContent(); if (responseBodyAsStream == null) { LOG.warn("POST request has no response body"); return objectMapper.readTree(EMPTY_JSON_TREE); } return objectMapper.readTree(responseBodyAsStream); } catch (Exception e) { LOG.error(e); return null; } finally { // Release httpclient resources uploadRequest.abort(); httpConnectionManager.shutdown(); // Delete cache file deleteCacheFile(); } }
From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java
@Test @SuppressWarnings("deprecation") public void testConnectionManagerAndProxy() throws Exception { HttpParams params = new BasicHttpParams(); Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); SchemeRegistry sr = new SchemeRegistry(); sr.register(http);//from www. j ava 2 s. c om ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr); DefaultHttpClient httpClient = new DefaultHttpClient(cm, params); // ? HTTP? String proxyHost = "proxy.wdf.sap.corp"; int proxyPort = 8080; httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials("", "")); HttpHost proxy = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); // ? HTTP? HttpRoutePlanner routePlanner = new HttpRoutePlanner() { public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { return new HttpRoute(target, null, new HttpHost("proxy.wdf.sap.corp", 8080), true); } }; // httpClient.setRoutePlanner(routePlanner); String[] urisToGet = { "http://119.29.234.42/", // "http://119.29.234.42/solr", // "http://119.29.234.42/jenkins", // "http://119.29.234.42/jenkins/manage", // "http://119.29.234.42/jenkins/credential-store", // }; // ?URI GetThread[] threads = new GetThread[urisToGet.length]; for (int i = 0; i < threads.length; i++) { HttpGet httpget = new HttpGet(urisToGet[i]); threads[i] = new GetThread(httpClient, httpget); } // for (int j = 0; j < threads.length; j++) { threads[j].start(); } // ? for (int j = 0; j < threads.length; j++) { threads[j].join(); } cm.closeIdleConnections(40, TimeUnit.SECONDS); cm.closeExpiredConnections(); }
From source file:org.ovirt.engine.sdk.web.ConnectionsPoolBuilder.java
/** * Creates DefaultHttpClient/* w ww . ja v a 2 s.c om*/ * * @param url * @param username * @param password * @param key_file * @param cert_file * @param ca_file * @param port * @param requestTimeout * * @return {@link DefaultHttpClient} */ private DefaultHttpClient createDefaultHttpClient(String url, String username, String password, String key_file, String cert_file, String ca_file, Integer port, Integer requestTimeout) { int port_ = getPort(url, port); DefaultHttpClient client = new DefaultHttpClient(createPoolingClientConnectionManager(url, port_)); if (requestTimeout != null && requestTimeout.intValue() != -1) { HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, requestTimeout.intValue()); DefaultHttpClient.setDefaultHttpParams(httpParams); } if (!StringUtils.isNulOrEmpty(username)) client.getCredentialsProvider().setCredentials(new AuthScope(getHost(url), port_), new UsernamePasswordCredentials(username, password)); // FIXME: use all .ctr params return client; }
From source file:net.billylieurance.azuresearch.AbstractAzureSearchQuery.java
/** * Run the query that has been set up in this instance. * Next step would be to get the results with {@link getQueryResult()} *///from w ww. j av a 2 s. co m public void doQuery() { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(_targetHost.getHostName(), _targetHost.getPort()), new UsernamePasswordCredentials(this.getAppid(), this.getAppid())); URI uri; try { String full_path = getQueryPath(); String full_query = getUrlQuery(); uri = new URI(AZURESEARCH_SCHEME, AZURESEARCH_AUTHORITY, full_path, full_query, null); // Bing and java URI disagree about how to represent + in query // parameters. This is what we have to do instead... uri = new URI(uri.getScheme() + "://" + uri.getAuthority() + uri.getPath() + "?" + uri.getRawQuery().replace("+", "%2b").replace("'", "%27")); // System.out.println(uri.toString()); // log.log(Level.WARNING, uri.toString()); } catch (URISyntaxException e1) { e1.printStackTrace(); return; } HttpGet get = new HttpGet(uri); get.addHeader("Accept", "application/xml"); get.addHeader("Content-Type", "application/xml"); try { _responsePost = client.execute(get); _resEntity = _responsePost.getEntity(); if (this.getProcessHTTPResults()) { _rawResult = loadXMLFromStream(_resEntity.getContent()); this.loadResultsFromRawResults(); } // Adding an automatic HTTP Result to String really requires // Apache Commons IO. That would break // Android compatibility. I'm not going to do that unless I // re-implement IOUtils. } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } }
From source file:org.qi4j.library.shiro.web.WebRealmServiceTest.java
@Test public void test() throws IOException { DefaultHttpClient client = new DefaultHttpClient(); // Our request method HttpGet get = new HttpGet("http://127.0.0.1:" + port + "/"); HttpResponse response = client.execute(get); int status = response.getStatusLine().getStatusCode(); assertThat(String.valueOf(status).substring(0, 1) + "xx", is("4xx")); EntityUtils.consume(response.getEntity()); // Simple interceptor set as first interceptor in the protocol chain HttpRequestInterceptor preemptiveAuth = new BasicAuthRequestInterceptor(); client.addRequestInterceptor(preemptiveAuth, 0); // Set credentials UsernamePasswordCredentials creds = new UsernamePasswordCredentials("foo", "bar"); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); response = client.execute(get);//from w w w. jav a2 s. c o m status = response.getStatusLine().getStatusCode(); assertThat(status, is(200)); String result = new BasicResponseHandler().handleResponse(response).trim(); assertThat(result, is("FOO")); }
From source file:com.marklogic.sesame.functionaltests.util.ConnectedRESTQA.java
public static String[] getHosts() { try {/*www. j a v a 2s.co m*/ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); HttpGet get = new HttpGet("http://localhost:8002" + "/manage/v2/hosts?format=json"); HttpResponse response = client.execute(get); ResponseHandler<String> handler = new BasicResponseHandler(); String body = handler.handleResponse(response); JsonNode actualObj = new ObjectMapper().readTree(body); JsonNode nameNode = actualObj.path("host-default-list").path("list-items"); //.path("meta").path("list-items").path("list-item"); List<String> hosts = nameNode.findValuesAsText("nameref"); String[] s = new String[hosts.size()]; hosts.toArray(s); return s; } catch (Exception e) { // writing error to Log e.printStackTrace(); } return null; }