类org.apache.http.impl.client.HttpClientBuilder源码实例Demo

下面列出了怎么用org.apache.http.impl.client.HttpClientBuilder的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: cubeai   文件: NexusArtifactClient.java
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
源代码2 项目: chaos-lemur   文件: StandardDirectorUtils.java
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
        new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
        .useTLS()
        .build();

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create()
        .disableRedirectHandling()
        .setDefaultCredentialsProvider(credentialsProvider)
        .setSSLSocketFactory(connectionFactory)
        .build();

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);

    return restTemplate;
}
 
源代码3 项目: mumu   文件: HttpClientUtil.java
/**
 * httpClient post 获取资源
 * @param url
 * @param params
 * @return
 */
public static String post(String url, Map<String, Object> params) {
	log.info(url);
	try {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);
		if (params != null && params.size() > 0) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				Object object = params.get(key);
				nvps.add(new BasicNameValuePair(key, object==null?null:object.toString()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
		}
		CloseableHttpResponse response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	} catch (Exception e) {
		log.error(e);
	}
	return null;
}
 
private HttpClientBuilder createHttpClientBuilder(boolean useKey) throws WxPayException {
  HttpClientBuilder httpClientBuilder = HttpClients.custom();
  if (useKey) {
    this.initSSLContext(httpClientBuilder);
  }

  if (StringUtils.isNotBlank(this.getConfig().getHttpProxyHost())
    && this.getConfig().getHttpProxyPort() > 0) {
    // 使用代理服务器 需要用户认证的代理服务器
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
      new AuthScope(this.getConfig().getHttpProxyHost(), this.getConfig().getHttpProxyPort()),
      new UsernamePasswordCredentials(this.getConfig().getHttpProxyUsername(), this.getConfig().getHttpProxyPassword()));
    httpClientBuilder.setDefaultCredentialsProvider(provider);
  }
  return httpClientBuilder;
}
 
源代码5 项目: teammates   文件: HttpRequest.java
/**
 * Executes a HTTP GET request and returns the response string.
 * @param uri The URI containing the request URL and request parameters.
 * @return the HTTP response string after executing the GET request
 */
public static String executeGetRequest(URI uri) throws IOException {
    HttpUriRequest request = new HttpGet(uri);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT_IN_MS).build();

    HttpResponse httpResponse = HttpClientBuilder.create()
                                                 .setDefaultRequestConfig(requestConfig)
                                                 .build()
                                                 .execute(request);
    HttpEntity entity = httpResponse.getEntity();
    String response = EntityUtils.toString(entity, "UTF-8");

    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response;
    } else {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), response);
    }
}
 
@Test
public void assertCustomConfig() throws Exception {
	HttpClient httpClient = HttpClientBuilder.create().build();
	HttpComponentsClientHttpRequestFactory hrf = new HttpComponentsClientHttpRequestFactory(httpClient);
	hrf.setConnectTimeout(1234);
	hrf.setConnectionRequestTimeout(4321);
	hrf.setReadTimeout(4567);

	URI uri = new URI(baseUrl + "/status/ok");
	HttpComponentsClientHttpRequest request = (HttpComponentsClientHttpRequest)
			hrf.createRequest(uri, HttpMethod.GET);

	Object config = request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);
	assertNotNull("Request config should be set", config);
	assertTrue("Wrong request config type" + config.getClass().getName(),
			RequestConfig.class.isInstance(config));
	RequestConfig requestConfig = (RequestConfig) config;
	assertEquals("Wrong custom connection timeout", 1234, requestConfig.getConnectTimeout());
	assertEquals("Wrong custom connection request timeout", 4321, requestConfig.getConnectionRequestTimeout());
	assertEquals("Wrong custom socket timeout", 4567, requestConfig.getSocketTimeout());
}
 
源代码7 项目: keycloak   文件: LogoutTest.java
@Test
public void postLogoutWithExpiredIdToken() throws Exception {
    oauth.doLogin("[email protected]", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

    oauth.clientSessionState("client-session");
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
    String idTokenString = tokenResponse.getIdToken();

    // Logout should succeed with expired ID token, see KEYCLOAK-3399
    setTimeOffset(60 * 60 * 24);

    String logoutUrl = oauth.getLogoutUrl()
      .idTokenHint(idTokenString)
      .postLogoutRedirectUri(oauth.APP_AUTH_ROOT)
      .build();

    try (CloseableHttpClient c = HttpClientBuilder.create().disableRedirectHandling().build();
      CloseableHttpResponse response = c.execute(new HttpGet(logoutUrl))) {
        assertThat(response, Matchers.statusCodeIsHC(Status.FOUND));
        assertThat(response.getFirstHeader(HttpHeaders.LOCATION).getValue(), is(oauth.APP_AUTH_ROOT));
    }
}
 
public CloseableHttpResponse post(String url, ContentType contentType, String data, String username, String password) {
    logger.debug("{}: Sending POST request url={} contentType={} data={}", applianceId, url, contentType, data);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    withUsernameAndPassword(httpClientBuilder, username, password);
    CloseableHttpClient client = httpClientBuilder.setDefaultRequestConfig(getRequestConfig()).build();
    try {
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(data, contentType));
        CloseableHttpResponse response = client.execute(request);
        return logResponse(response);
    }
    catch(IOException e) {
        logger.error("{}: Error executing POST", applianceId, e);
        return null;
    }
}
 
源代码9 项目: pnc   文件: AbstractImportTest.java
protected String download(String url) throws Exception {
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    String content = null;
    InputStream stream = null;
    try {
        client = HttpClientBuilder.create().build();
        response = client.execute(new HttpGet(url));
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

        stream = response.getEntity().getContent();
        content = IOUtils.toString(stream, "UTF-8");
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }

    return content;
}
 
源代码10 项目: vespa   文件: FlagsClient.java
private static CloseableHttpClient createClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
    DelayedConnectionLevelRetryHandler retryHandler = DelayedConnectionLevelRetryHandler.Builder
            .withExponentialBackoff(Duration.ofSeconds(1), Duration.ofSeconds(20), 5)
            .build();
    return HttpClientBuilder.create()
            .setUserAgent("controller-flags-v1-client")
            .setSSLContext(identityProvider.getIdentitySslContext())
            .setSSLHostnameVerifier(new FlagTargetsHostnameVerifier(targets))
            .setDefaultRequestConfig(RequestConfig.custom()
                                             .setConnectTimeout((int) Duration.ofSeconds(10).toMillis())
                                             .setConnectionRequestTimeout((int) Duration.ofSeconds(10).toMillis())
                                             .setSocketTimeout((int) Duration.ofSeconds(20).toMillis())
                                             .build())
            .setMaxConnPerRoute(2)
            .setMaxConnTotal(100)
            .setRetryHandler(retryHandler)
            .build();
}
 
源代码11 项目: amex-api-java-client-core   文件: ApiClientTest.java
@Test(expected = ExecutorException.class)
public void executeGet() throws Exception {

    ApiClient devPortalExecutor = new ApiClient.DevPortalExecutorBuilder()
            .setEndpoint(EndPoint.PRODUCTION)
            .setSigningInformation("RS256", "kid", "")
            .setTokenRequesterId("token")
            .createDevPortalExecutor();

    setTestOverride(devPortalExecutor, true);
    Field field = devPortalExecutor.getClass().getDeclaredField("httpClient");
    field.setAccessible(true);
    field.set(devPortalExecutor, HttpClientBuilder.create().build());
    AuthProvider authProvider = Mockito.mock(HmacAuthProvider.class);
    assertNotNull(devPortalExecutor.execute(
            new StatusRequest.StatusRequestBuilder().createStatusRequest(), authProvider));
}
 
private String performPayPalApiCall(final String endpoint, final String callParams) throws IOException {

        if (LOG.isDebugEnabled()) {
            LOG.debug("PayPal NPV call:\n{}", callParams.replace('&', '\n'));
        }

        final StringBuilder respBuilder = new StringBuilder();

        final HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setEntity(new StringEntity(callParams));

        final HttpClient client = HttpClientBuilder.create().build();

        final HttpResponse response = client.execute(httpPost);
        final BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));

        String _line;
        while (((_line = rd.readLine()) != null)) {
            respBuilder.append(_line);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("PayPal NPV response:\n{}", respBuilder.toString().replace('&', '\n'));
        }
        return respBuilder.toString();
    }
 
源代码13 项目: pacbot   文件: CommonUtils.java
public static String doHttpPost(String uri, String token, String accessToken) throws Exception {

		HttpPost httpPost = new HttpPost(uri);
		httpPost.addHeader("content-type", "application/json");
		httpPost.addHeader("cache-control", "no-cache");
		if (!Strings.isNullOrEmpty(token)) {
			httpPost.addHeader("Authorization", token + " " + accessToken);
		}
		HttpClient httpClient = HttpClientBuilder.create().build();
		if (httpClient != null) {
			HttpResponse httpResponse;
			try {
				httpResponse = httpClient.execute(httpPost);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					return EntityUtils.toString(httpResponse.getEntity());
				} else {
					throw new Exception("unable to execute post request caused by"
							+ EntityUtils.toString(httpResponse.getEntity()));
				}
			} catch (Exception e) {
				logger.error("Error getting the data ", e);
				throw e;
			}
		}
		return "{}";
	}
 
源代码14 项目: riptide   文件: HttpClientFactory.java
private static HttpClientBuilder configureCaching(final Caching caching,
        @Nullable final Object cacheStorage) {
    final Heuristic heuristic = caching.getHeuristic();

    final CacheConfig.Builder config = CacheConfig.custom()
            .setSharedCache(caching.getShared())
            .setMaxObjectSize(caching.getMaxObjectSize())
            .setMaxCacheEntries(caching.getMaxCacheEntries());

    if (heuristic.getEnabled()) {
        config.setHeuristicCachingEnabled(true);
        config.setHeuristicCoefficient(heuristic.getCoefficient());
        config.setHeuristicDefaultLifetime(heuristic.getDefaultLifeTime().to(TimeUnit.SECONDS));
    }

    @Hack("return cast tricks classloader in case of missing httpclient-cache")
    CachingHttpClientBuilder builder = CachingHttpClients.custom()
                                                         .setCacheConfig(config.build())
                                                         .setHttpCacheStorage((HttpCacheStorage) cacheStorage)
                                                         .setCacheDir(Optional.ofNullable(caching.getDirectory())
                                                                              .map(Path::toFile)
                                                                              .orElse(null));
    return HttpClientBuilder.class.cast(builder);
}
 
private void loginApi(GlobalConfigDataForSonarInstance globalConfigDataForSonarInstance) {

        httpClientContext = HttpClientContext.create();
        httpClient = HttpClientBuilder.create().build();

        if (StringUtils.isNotEmpty(globalConfigDataForSonarInstance.getToken())) {
            token = globalConfigDataForSonarInstance.getToken();
        } else {
            HttpPost loginHttpPost = new HttpPost(globalConfigDataForSonarInstance.getSonarUrl() + getSonarApiLogin());

            List<NameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("login", globalConfigDataForSonarInstance.getUsername()));
            nvps.add(new BasicNameValuePair("password", globalConfigDataForSonarInstance.getPass()));
            nvps.add(new BasicNameValuePair("remember_me", "1"));
            loginHttpPost.setEntity(createEntity(nvps));
            loginHttpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            executePostRequest(httpClient, loginHttpPost);
        }

        logged = true;
    }
 
源代码16 项目: jshERP   文件: HttpClient.java
/**
 * 采用Post方式发送请求,获取响应数据
 *
 * @param url        url地址
 * @param param  参数值键值对的字符串
 * @return
 */
public static String httpPost(String url, String param) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpPost post = new HttpPost(url);
        EntityBuilder builder = EntityBuilder.create();
        builder.setContentType(ContentType.APPLICATION_JSON);
        builder.setText(param);
        post.setEntity(builder.build());

        CloseableHttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        logger.info("状态:"+statusCode+"数据:"+data);
        return data;
    } catch(Exception e){
        throw new RuntimeException(e.getMessage());
    } finally {
        try{
            client.close();
        }catch(Exception ex){ }
    }
}
 
源代码17 项目: pacbot   文件: HttpUtil.java
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
/**
 * Call the conduit API of Phabricator
 *
 * @param action Name of the API call
 * @param params The data to send to Harbormaster
 * @return The result as a JSONObject
 * @throws IOException If there was a problem reading the response
 * @throws ConduitAPIException If there was an error calling conduit
 */
public JSONObject perform(String action, JSONObject params) throws IOException, ConduitAPIException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest request = createRequest(action, params);

    HttpResponse response;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        throw new ConduitAPIException(e.getMessage());
    }

    InputStream responseBody = response.getEntity().getContent();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ConduitAPIException(IOUtils.toString(responseBody, Charset.defaultCharset()), response.getStatusLine().getStatusCode());
    }

    JsonSlurper jsonParser = new JsonSlurper();
    return (JSONObject) jsonParser.parse(responseBody);
}
 
源代码19 项目: couchbase-jvm-core   文件: ClusterDependentTest.java
/**
 * Helper (hacked together) method to grab a config from a bucket without having to initialize the
 * client first - this helps with pre-bootstrap decisions like credentials for RBAC.
 */
public static int[] minClusterVersion() throws Exception {
    int port = 8091;
    if (useMock) {
        port = mock().getHttpPort();
    }
    URIBuilder builder = new URIBuilder();
    builder.setScheme("http").setHost(seedNode).setPort(port).setPath("/pools/default/buckets/" + bucket)
        .setParameter("bucket", bucket);
    HttpGet request = new HttpGet(builder.build());
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(seedNode, port), new UsernamePasswordCredentials(adminUser, adminPassword));
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
    HttpResponse response = client.execute(request);
    int status = response.getStatusLine().getStatusCode();
    if (status < 200 || status > 300) {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
    String rawConfig = EntityUtils.toString(response.getEntity());
    return minNodeVersionFromConfig(rawConfig);
}
 
源代码20 项目: vespa   文件: ConfigServerApiImpl.java
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(200); // Increase max total connections to 200, which should be enough

    // Have experienced hang in socket read, which may have been because of
    // system defaults, therefore set explicit timeouts.
    return HttpClientBuilder.create()
            .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG)
            .disableAutomaticRetries()
            .setUserAgent("node-admin")
            .setConnectionManager(cm)
            .build();
}
 
源代码21 项目: Openfire   文件: FaviconServlet.java
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    // Create a pool of HTTP connections to use to get the favicons
    client = HttpClientBuilder.create()
        .setConnectionManager(new PoolingHttpClientConnectionManager())
        .setRedirectStrategy(new LaxRedirectStrategy())
        .build();
    // Load the default favicon to use when no favicon was found of a remote host
    try {
       defaultBytes = Files.readAllBytes(Paths.get(JiveGlobals.getHomeDirectory(), "plugins/admin/webapp/images/server_16x16.gif"));
    }
    catch (final IOException e) {
        LOGGER.warn("Unable to retrieve default favicon", e);
    }
    // Initialize caches.
    missesCache = CacheFactory.createCache("Favicon Misses");
    hitsCache = CacheFactory.createCache("Favicon Hits");
}
 
源代码22 项目: signalfx-java   文件: AWSInstanceInfo.java
/**
 * Attempt to get the value for the AWSUniqueId dimension used in SignalFx AWS integrations.
 *
 * @param timeoutInMs
 *            how long to wait in milliseconds for AWS to respond
 * @return null if the value was not obtained for any reason
 */
public static String get(int timeoutInMs) {
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutInMs).build();
    HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .build();
    HttpGet request = new HttpGet(URL);

    try {
        HttpResponse response = client.execute(request);
        JsonNode object = MAPPER.readTree(response.getEntity().getContent());

        return object.get(INSTANCE_ID).asText() + "_" + object.get(REGION).asText() + "_"
                + object.get(ACCOUNT_ID).asText();

    } catch (Exception e) {
        log.trace("Exception trying to execute {}, Exception: {} ", request, e);
    }

    return null;
}
 
源代码23 项目: FishingBot   文件: RealmsAPI.java
public RealmsAPI(AuthData authData) {
    BasicCookieStore cookies = new BasicCookieStore();

    BasicClientCookie sidCookie = new BasicClientCookie("sid", String.join(":", "token", authData.getAccessToken(), authData.getProfile()));
    BasicClientCookie userCookie = new BasicClientCookie("user", authData.getUsername());
    BasicClientCookie versionCookie = new BasicClientCookie("version", ProtocolConstants.getVersionString(FishingBot.getInstance().getServerProtocol()));

    sidCookie.setDomain(".pc.realms.minecraft.net");
    userCookie.setDomain(".pc.realms.minecraft.net");
    versionCookie.setDomain(".pc.realms.minecraft.net");

    sidCookie.setPath("/");
    userCookie.setPath("/");
    versionCookie.setPath("/");

    cookies.addCookie(sidCookie);
    cookies.addCookie(userCookie);
    cookies.addCookie(versionCookie);

    client = HttpClientBuilder.create()
            .setDefaultCookieStore(cookies)
            .build();
}
 
/** Gets the number of bytes the server has received. */
private long getReceivedByteCount(String uploadUrl) throws IOException {
  HttpPost httpPost = createAuthenticatedPostRequest(uploadUrl);
  httpPost.addHeader(UPLOAD_PROTOCOL_HEADER, UPLOAD_PROTOCOL_VALUE);
  httpPost.addHeader(UPLOAD_COMMAND_HEADER, UploadCommands.QUERY);

  CloseableHttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build();
  HttpResponse response = httpClient.execute(httpPost);

  if (response.getFirstHeader(UPLOAD_GRANULARITY_HEADER) != null) {
    updateOptimalChunkSize(
        Integer.parseInt(response.getFirstHeader(UPLOAD_GRANULARITY_HEADER).getValue()));
  }

  switch (response.getFirstHeader(UPLOAD_STATUS_HEADER).getValue()) {
    case UploadStatuses.ACTIVE:
      return Long.parseLong(response.getFirstHeader(RECEIVED_BYTE_COUNT_HEADER).getValue());
    case UploadStatuses.FINAL:
      return request.getFileSize();
    default:
      throw new IllegalStateException(ExceptionStrings.INVALID_UPLOAD_STATUS);
  }
}
 
源代码25 项目: hadoop-ozone   文件: LogSubcommand.java
private void streamLog(OzoneConfiguration conf, Component logComponent,
    List<LoggerSource> loggers, Predicate<String> filter) {
  HttpClient client = HttpClientBuilder.create().build();

  HttpGet get = new HttpGet(getHost(conf, logComponent) + "/logstream");
  try {
    HttpResponse execute = client.execute(get);
    try (BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(execute.getEntity().getContent(),
            StandardCharsets.UTF_8))) {
      bufferedReader.lines()
          .filter(line -> {
            for (LoggerSource logger : loggers) {
              if (line.contains(logger.getLoggerName()) && filter
                  .test(line)) {
                return true;
              }
            }
            return false;
          })
          .map(this::processLogLine)
          .map(l -> "[" + logComponent.prefix() + "] " + l)
          .forEach(System.out::println);
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
源代码26 项目: tutorials   文件: AppLiveTest.java
@Test
public void givenBasicRoute_whenPut_thenCorrectOutput() throws Exception {
    final HttpUriRequest request = new HttpPut("http://localhost:9000/basic-route-example");
    try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
        .build()
        .execute(request);) {
        assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("PUT called");
    }
}
 
源代码27 项目: ephemerals   文件: WireMockEphemeralTest.java
@Test
public void test() throws IOException {
    URL url = wireMockResource.get();
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url.toString()+"/get/this");
    HttpResponse response = client.execute(request);
    Assert.assertEquals(200,response.getStatusLine().getStatusCode());
}
 
源代码28 项目: dependency-track   文件: ManagedHttpClientTest.java
@Test
public void objectTest() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setConnectionManager(connectionManager);
    CloseableHttpClient client = clientBuilder.build();
    ManagedHttpClient managedHttpClient = new ManagedHttpClient(client, connectionManager);
    Assert.assertSame(client, managedHttpClient.getHttpClient());
    Assert.assertSame(connectionManager, managedHttpClient.getConnectionManager());
}
 
源代码29 项目: mycore   文件: MCRHttpsClient.java
public static CloseableHttpClient getHttpsClient() {
    return HttpClientBuilder
        .create()
        .setConnectionTimeToLive(1, TimeUnit.MINUTES)
        .setSSLContext(SSLContexts.createSystemDefault())
        .build();
}
 
源代码30 项目: SolRDF   文件: IntegrationTestSupertypeLayer.java
/**
 * Initilisation procedure for this test case.
 * 
 * @throws UnableToBuildSolRDFClientException in case the client cannot be built.
 * @throws Exception in case of Solr startup failure.
 */
@BeforeClass
public static void initITTest() {
	System.setProperty("tests.asserts", "false");	
	System.setProperty("jetty.port", "8080");
	System.setProperty("solr.core.name", "store");
	System.setProperty("solr.data.dir", initCoreDataDir.getAbsolutePath());
		
	try {
		SOLR = createJetty(
				"target/solrdf-integration-tests-1.1-dev/solrdf",
				JettyConfig.builder()
					.setPort(8080)
					.setContext("/solr")
					.stopAtShutdown(true)
					.build());		
		
		final HttpClient httpClient = HttpClientBuilder.create()
				.setRoutePlanner(
						new DefaultRoutePlanner(
								new SchemePortResolver() {
									@Override
									public int resolve(final HttpHost host) throws UnsupportedSchemeException {
										return SOLR.getLocalPort();
									}
								})).build();
		
		
		SOLRDF_CLIENT = SolRDF.newBuilder()
	              .withEndpoint("http://127.0.0.1:8080/solr/store")
	              .withGraphStoreProtocolEndpointPath("/rdf-graph-store")
	              .withHttpClient(httpClient)
	              .withSPARQLEndpointPath("/sparql")
	              .build();
		
		PLAIN_SOLR_CLIENT = new HttpSolrClient(SOLR_URI);
	} catch (final Exception exception) {
		throw new RuntimeException(exception);
	}
}
 
 同包方法