Beispiel #1
0
 protected void configClient(HttpClientBuilder cb, Settings settings) throws HTTPException {
   cb.useSystemProperties();
   String agent = (String) settings.get(Prop.USER_AGENT);
   if (agent != null) cb.setUserAgent(agent);
   setInterceptors(cb);
   cb.setContentDecoderRegistry(contentDecoderMap);
 }
Beispiel #2
0
 /**
  * Called primarily from HTTPMethod to do the bulk of the execution. Assumes HTTPMethod has
  * inserted its headers into request.
  *
  * @param method
  * @param methoduri
  * @param rb
  * @return Request+Response pair
  * @throws HTTPException
  */
 ExecState execute(HTTPMethod method, URI methoduri, RequestBuilder rb) throws HTTPException {
   this.execution = new ExecState();
   this.requestURI = methoduri;
   AuthScope methodscope = HTTPAuthUtil.uriToAuthScope(methoduri);
   AuthScope target = HTTPAuthUtil.authscopeUpgrade(this.scope, methodscope);
   synchronized (this) { // keep coverity happy
     // Merge Settings;
     Settings merged = HTTPUtil.merge(globalsettings, localsettings);
     if (!this.cachevalid) {
       RequestConfig.Builder rcb = RequestConfig.custom();
       this.cachedconfig = configureRequest(rcb, merged);
       HttpClientBuilder cb = HttpClients.custom();
       configClient(cb, merged);
       setAuthenticationAndProxy(cb);
       this.cachedclient = cb.build();
       rb.setConfig(this.cachedconfig);
       this.cachevalid = true;
     }
   }
   this.execution.request = (HttpRequestBase) rb.build();
   try {
     HttpHost targethost = HTTPAuthUtil.authscopeToHost(target);
     this.execution.response =
         cachedclient.execute(targethost, this.execution.request, this.sessioncontext);
   } catch (IOException ioe) {
     throw new HTTPException(ioe);
   }
   return this.execution;
 }
  @BeforeClass
  public static void beforeClass() throws Exception {
    ourPort = PortUtil.findFreePort();
    ourServer = new Server(ourPort);

    DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider();

    ServletHandler proxyHandler = new ServletHandler();
    ourServlet = new RestfulServer();
    ourServlet.getFhirContext().setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator());
    ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(10));

    ourServlet.setResourceProviders(patientProvider, new DummyObservationResourceProvider());
    ServletHolder servletHolder = new ServletHolder(ourServlet);
    proxyHandler.addServletWithMapping(servletHolder, "/*");
    ourServer.setHandler(proxyHandler);
    ourServer.start();

    PoolingHttpClientConnectionManager connectionManager =
        new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(connectionManager);
    ourClient = builder.build();

    ourDefaultAddressStrategy = ourServlet.getServerAddressStrategy();
  }
  private static CloseableHttpClient createHTTPClient(
      PrivateKey privateKey, X509Certificate certificate, boolean validateCertificate) {
    // HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    HttpClientBuilder clientBuilder = HttpClients.custom();
    try {
      SSLContext sslContext =
          TrustUtils.getCustomSSLContext(privateKey, certificate, validateCertificate);
      clientBuilder.setSslcontext(sslContext);
    } catch (KeyStoreException
        | NoSuchAlgorithmException
        | CertificateException
        | IOException
        | KeyManagementException
        | UnrecoverableKeyException
        | NoSuchProviderException ex) {
      LOGGER.log(Level.WARNING, "unable to set SSL context", ex);
      return null;
    }

    RequestConfig.Builder rcBuilder = RequestConfig.custom();
    // handle redirects :)
    rcBuilder.setRedirectsEnabled(true);
    // HttpClient bug caused by Lighttpd
    rcBuilder.setExpectContinueEnabled(false);
    clientBuilder.setDefaultRequestConfig(rcBuilder.build());

    // create connection manager
    // ClientConnectionManager connMgr = new SingleClientConnManager(params, registry);

    // return new DefaultHttpClient(connMgr, params);
    return clientBuilder.build();
  }
  public String getPageContent(String uri) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    HttpClient httpClient = httpClientBuilder.build();
    HttpUriRequest httpReq = new HttpGet(uri);
    HttpResponse httpResp = null;
    HttpEntity httpEntity = null;
    try {
      httpResp = httpClient.execute(httpReq);
      httpEntity = httpResp.getEntity();
      if (httpEntity != null) {
        InputStream is = httpEntity.getContent();
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
        writer.close();
        is.close();
        return writer.toString();
      }
    } catch (IOException e) {
      logger.error("获取网页内容时,发生异常,具体为:{}", e);
      return StringUtils.EMPTY;
    } finally {
      httpReq.abort();
      try {
        EntityUtils.consume(httpEntity);
      } catch (Exception e2) {

      }
    }
    return StringUtils.EMPTY;
  }
 /** Executes the request against the appliance API (Should not be called directly). */
 @Override
 public MuteCheckResponse executeRequest() throws MorpheusApiRequestException {
   CloseableHttpClient client = null;
   try {
     URIBuilder uriBuilder = new URIBuilder(endpointUrl);
     uriBuilder.setPath("/api/monitoring/checks/" + this.getCheckId() + "/quarantine");
     HttpPut request = new HttpPut(uriBuilder.build());
     this.applyHeaders(request);
     HttpClientBuilder clientBuilder = HttpClients.custom();
     clientBuilder.setDefaultRequestConfig(this.getRequestConfig());
     client = clientBuilder.build();
     request.addHeader("Content-Type", "application/json");
     request.setEntity(new StringEntity(generateRequestBody()));
     CloseableHttpResponse response = client.execute(request);
     return MuteCheckResponse.createFromStream(response.getEntity().getContent());
   } catch (Exception ex) {
     // Throw custom exception
     throw new MorpheusApiRequestException(
         "Error Performing API Request for muting/unmuting a Check", ex);
   } finally {
     if (client != null) {
       try {
         client.close();
       } catch (IOException io) {
         // ignore
       }
     }
   }
 }
  @BeforeClass
  public static void beforeClass() throws Exception {
    ourPort = PortUtil.findFreePort();
    ourServer = new Server(ourPort);

    PatientProvider patientProvider = new PatientProvider();

    ourReportProvider = new DiagnosticReportProvider();

    ServletHandler proxyHandler = new ServletHandler();
    RestfulServer servlet = new RestfulServer(ourCtx);
    servlet.setResourceProviders(
        patientProvider,
        ourReportProvider,
        new ObservationProvider(),
        new OrganizationResourceProvider());
    ServletHolder servletHolder = new ServletHolder(servlet);
    proxyHandler.addServletWithMapping(servletHolder, "/*");
    ourServer.setHandler(proxyHandler);
    ourServer.start();

    PoolingHttpClientConnectionManager connectionManager =
        new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(connectionManager);
    ourClient = builder.build();
  }
  public void afterPropertiesSet() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager());

    if ((_login != null) && (_password != null)) {
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

      credentialsProvider.setCredentials(
          new AuthScope(_hostName, _hostPort), new UsernamePasswordCredentials(_login, _password));

      httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
      httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl());
    } else {
      if (_logger.isWarnEnabled()) {
        _logger.warn("Login and password are required");
      }
    }

    try {
      setProxyHost(httpClientBuilder);

      _closeableHttpClient = httpClientBuilder.build();

      if (_logger.isDebugEnabled()) {
        _logger.debug("Configured client for " + _protocol + "://" + _hostName);
      }
    } catch (Exception e) {
      _logger.error("Unable to configure client", e);
    }
  }
Beispiel #9
0
    public Builder setKerberosAuth(GSSCredentialProvider gssCrendentialProvider) {
      Credentials creds =
          new Credentials() {
            @Override
            public String getPassword() {
              return null;
            }

            @Override
            public Principal getUserPrincipal() {
              return null;
            }
          };
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(
          new AuthScope(_host, _port, AuthScope.ANY_REALM, AuthSchemes.SPNEGO), creds);
      _httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

      AuthSchemeProvider authSchemaProvider =
          gssCrendentialProvider == null
              ? new SPNegoSchemeFactory(true)
              : new BasicSPNegoSchemeFactory(true, gssCrendentialProvider);

      _httpClientBuilder.setDefaultAuthSchemeRegistry(
          RegistryBuilder.<AuthSchemeProvider>create()
              .register(AuthSchemes.SPNEGO, authSchemaProvider)
              .build());
      return this;
    }
 /** HttpClient 4.3简单入门---HttpPost */
 @Test
 public void test02() {
   HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
   CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
   HttpPost httpPost = new HttpPost(HTTPPOSTTESTURL);
   //		httpPost.setConfig();
   List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数列表
   formParams.add(new BasicNameValuePair("type", "all"));
   formParams.add(new BasicNameValuePair("query", "httpClient"));
   formParams.add(new BasicNameValuePair("sort", ""));
   UrlEncodedFormEntity entity;
   try {
     entity = new UrlEncodedFormEntity(formParams, "UTF-8");
     httpPost.setEntity(entity);
     HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
     HttpEntity httpEntity = httpResponse.getEntity();
     if (httpEntity != null) {
       logger.info("response:{}", EntityUtils.toString(httpEntity, "UTF-8"));
     }
     closeableHttpClient.close(); // 释放资源
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  public static void main(String[] args) throws Exception {
    HttpGet get = new HttpGet("https://localhost/docs/index.html");
    HttpClientBuilder client = HttpClientBuilder.create();

    ServerConfig config = new ServerConfig(new Properties());
    config.setParam("https.keyStoreFile", "test.keystore");
    config.setParam("https.keyPassword", "nopassword");
    config.setParam("https.keyStoreType", "JKS");
    config.setParam("https.protocol", "SSLv3");

    // SSLContextCreator ssl = new SSLContextCreator(config);
    // SSLContext ctx = ssl.getSSLContext();

    //		ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
    //				client.getConnectionManager().getSchemeRegistry(),
    //				ProxySelector.getDefault());
    //		client.setRoutePlanner(routePlanner);

    // SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
    //		socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    // DefaultSchemePortResolver sch = new DefaultSchemePortResolver();
    // sch.("https", 443, socketFactory);
    // CloseableHttpClient c = client.build();
    // getConnectionManager().getSchemeRegistry().register(sch);
    HttpResponse response = client.build().execute(get);
    System.out.println(response.getStatusLine().getStatusCode());
  }
  /** HttpClient 4.3 简单入门---HttpGet */
  @Test
  public void test01() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // 创建httpClientBuilder
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); // 创建httpClient
    HttpGet httpGet = new HttpGet(HTTPGETTESTURL);
    logger.info("httpGet.getRequestLine():{}", httpGet.getRequestLine());

    try {
      HttpResponse httpResponse = closeableHttpClient.execute(httpGet); // 执行get请求
      HttpEntity httpEntity = httpResponse.getEntity(); // 获取响应消息实体
      logger.info("响应状态:{}", httpResponse.getStatusLine());
      if (httpEntity != null) {
        logger.info("contentEncoding:{}", httpEntity.getContentEncoding());
        logger.info("response content:{}", EntityUtils.toString(httpEntity));
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        closeableHttpClient.close(); // 关闭流并释放资源
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  private static HttpClient getHttpClient() {

    try {
      SSLContext sslContext = SSLContext.getInstance("SSL");

      sslContext.init(
          null,
          new TrustManager[] {
            new X509TrustManager() {
              public X509Certificate[] getAcceptedIssuers() {

                return null;
              }

              public void checkClientTrusted(X509Certificate[] certs, String authType) {}

              public void checkServerTrusted(X509Certificate[] certs, String authType) {}
            }
          },
          new SecureRandom());

      SSLConnectionSocketFactory socketFactory =
          new SSLConnectionSocketFactory(
              sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build();

      return httpClient;

    } catch (Exception e) {
      e.printStackTrace();
      return HttpClientBuilder.create().build();
    }
  }
Beispiel #14
0
 /**
  * Prior to {@code Build()}, host, port, and endpoint must be specified.
  *
  * @return a {@link JobClient}.
  * @throws URISyntaxException
  */
 public JobClient build() throws URISyntaxException {
   // The definition of the following parameters are optional.
   if (_statusUpdateIntervalSeconds == null) {
     _statusUpdateIntervalSeconds = DEFAULT_STATUS_UPDATE_INTERVAL_SECONDS;
   }
   if (_batchRequestSize == null) {
     _batchRequestSize = DEFAULT_BATCH_REQUEST_SIZE;
   }
   if (_requestTimeoutSeconds == null) {
     _requestTimeoutSeconds = DEFAULT_REQUEST_TIMEOUT_SECONDS;
   }
   RequestConfig requestConfig =
       RequestConfig.custom()
           .setSocketTimeout(_requestTimeoutSeconds * 1000)
           .setConnectTimeout(_requestTimeoutSeconds * 1000)
           .setConnectionRequestTimeout(_requestTimeoutSeconds * 1000)
           .setStaleConnectionCheckEnabled(true)
           .build();
   _httpClientBuilder.setDefaultRequestConfig(requestConfig);
   _httpClientBuilder.setRetryHandler(new StandardHttpRequestRetryHandler());
   return new JobClient(
       Preconditions.checkNotNull(_host, "host must be set"),
       Preconditions.checkNotNull(_port, "port must be set"),
       Preconditions.checkNotNull(_endpoint, "endpoint must be set"),
       _statusUpdateIntervalSeconds,
       _batchRequestSize,
       _instanceDecorator,
       _httpClientBuilder.build());
 }
  @Override
  public void activateBrowserfeatures(final Upload upload) throws UnirestException {

    // Create a local instance of cookie store
    // Populate cookies if needed
    final CookieStore cookieStore = new BasicCookieStore();
    for (final PersistentCookieStore.SerializableCookie serializableCookie :
        upload.getAccount().getSerializeableCookies()) {
      final BasicClientCookie cookie =
          new BasicClientCookie(
              serializableCookie.getCookie().getName(), serializableCookie.getCookie().getValue());
      cookie.setDomain(serializableCookie.getCookie().getDomain());
      cookieStore.addCookie(cookie);
    }

    final HttpClient client =
        HttpClientBuilder.create().useSystemProperties().setDefaultCookieStore(cookieStore).build();
    Unirest.setHttpClient(client);

    final HttpResponse<String> response =
        Unirest.get(String.format(VIDEO_EDIT_URL, upload.getVideoid())).asString();

    changeMetadata(response.getBody(), upload);

    final RequestConfig clientConfig =
        RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000).build();
    Unirest.setHttpClient(HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).build());
  }
Beispiel #16
0
 private static CloseableHttpClient buildHttpClient(boolean isMultiThread) {
   HttpClientBuilder httpClientBuilder =
       HttpClientBuilder.create().setDefaultRequestConfig(buildRequestConfig());
   if (isMultiThread) {
     httpClientBuilder.setConnectionManager(bulidConnectionManager());
   }
   return httpClientBuilder.build();
 }
Beispiel #17
0
  private static HttpClient createHttpClient() {
    RequestConfig config =
        RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();

    HttpClientBuilder hcBuilder = HttpClients.custom();
    hcBuilder.setDefaultRequestConfig(config);

    return hcBuilder.build();
  }
 public void init() {
   if (httpClient == null) {
     RequestConfig.Builder requestBuilder = RequestConfig.custom();
     requestBuilder = requestBuilder.setConnectTimeout(bookmakerConfig.getTimeout());
     requestBuilder = requestBuilder.setConnectionRequestTimeout(bookmakerConfig.getTimeout());
     HttpClientBuilder builder = HttpClientBuilder.create();
     builder.setDefaultRequestConfig(requestBuilder.build());
     httpClient = builder.build();
   }
 }
  public void checkPermission(
      ExtractorLayerRequest request, String secureHost, String username, String roles)
      throws IOException {
    URL capabilitiesURL = request.capabilitiesURL("WFS", "1.0.0");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setUserAgent(this.userAgent);

    HttpClientContext localContext = HttpClientContext.create();
    final HttpHost httpHost =
        new HttpHost(
            capabilitiesURL.getHost(), capabilitiesURL.getPort(), capabilitiesURL.getProtocol());

    HttpGet get = new HttpGet(capabilitiesURL.toExternalForm());
    if (username != null
        && (secureHost.equalsIgnoreCase(request._url.getHost())
            || "127.0.0.1".equalsIgnoreCase(request._url.getHost())
            || "localhost".equalsIgnoreCase(request._url.getHost()))) {
      LOG.debug(
          "WfsExtractor.checkPermission - Secured Server: adding username header and role headers to request for checkPermission");

      addImpersonateUserHeaders(username, roles, get);

      enablePreemptiveBasicAuth(
          capabilitiesURL,
          httpClientBuilder,
          localContext,
          httpHost,
          _adminUsername,
          _adminPassword);
    } else {
      // use a user agent that does *not* trigger basic auth on remote server
      httpClientBuilder.setUserAgent("Apache-HttpClient");
      LOG.debug("WfsExtractor.checkPermission - Non Secured Server");
    }

    final CloseableHttpClient httpclient = httpClientBuilder.build();
    String capabilities =
        FileUtils.asString(
            httpclient.execute(httpHost, get, localContext).getEntity().getContent());
    Pattern regex =
        Pattern.compile(
            "(?m)<FeatureType[^>]*>(\\\\n|\\s)*<Name>\\s*(\\w*:)?"
                + Pattern.quote(request._layerName)
                + "\\s*</Name>");
    boolean permitted = regex.matcher(capabilities).find();

    if (!permitted) {
      throw new SecurityException(
          "User does not have sufficient privileges to access the Layer: "
              + request._layerName
              + ". \n\nCapabilities:  "
              + capabilities);
    }
  }
  protected void mockHttpClientBuilder(String fileName) throws Exception {
    PowerMockito.mockStatic(HttpClientBuilder.class);

    HttpClientBuilder httpClientbuilder = Mockito.mock(HttpClientBuilder.class);

    CloseableHttpClient closeableHttpClient = mockCloseableHttpClient(fileName);

    Mockito.when(httpClientbuilder.build()).thenReturn(closeableHttpClient);

    Mockito.when(HttpClientBuilder.create()).thenReturn(httpClientbuilder);
  }
 private HttpClient getHttpClient() {
   HttpClient client = null;
   if (proxyHost != null) {
     client =
         HttpClientBuilder.create()
             .setRoutePlanner(new DefaultProxyRoutePlanner(proxyHost))
             .build();
   } else {
     client = HttpClientBuilder.create().build();
   }
   return client;
 }
Beispiel #22
0
 static {
   HttpClientBuilder custom = HttpClients.custom();
   custom.setUserAgent("Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0");
   RequestConfig config =
       RequestConfig.custom()
           .setConnectionRequestTimeout(5 * 1000)
           .setSocketTimeout(30 * 1000)
           .setConnectTimeout(5 * 1000)
           .build();
   custom.setDefaultRequestConfig(config);
   httpclient = custom.build();
   minHttpclient = HttpClients.createMinimal();
 }
  public ConfiglessCustomHttpEngine() {
    super();
    HttpClientBuilder client = HttpClientBuilder.create();

    try {
      client.setSslcontext(createGullibleSslContext());
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    this.httpClient = client.build();
  }
  @Bean
  RestTemplate restTemplate() {

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    HttpClientBuilder httpClient =
        HttpClientBuilder.create().setConnectionManager(connectionManager);

    HttpComponentsClientHttpRequestFactory httpRequestFactory =
        new HttpComponentsClientHttpRequestFactory(httpClient.build());

    return new RestTemplate(httpRequestFactory);
  }
  public static String sendToRockBlockHttp(
      String destImei, String username, String password, byte[] data)
      throws HttpException, IOException {

    CloseableHttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost("https://secure.rock7mobile.com/rockblock/MT");
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("imei", destImei));
    urlParameters.add(new BasicNameValuePair("username", username));
    urlParameters.add(new BasicNameValuePair("password", password));
    urlParameters.add(new BasicNameValuePair("data", ByteUtil.encodeToHex(data)));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse response = client.execute(post);

    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
      result.append(line);
    }

    try {
      client.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result.toString();
  }
/** Unit tests for {@link Builder}. */
public class LBHttpSolrClientBuilderTest extends LuceneTestCase {
  private static final String ANY_BASE_SOLR_URL = "ANY_BASE_SOLR_URL";
  private static final HttpClient ANY_HTTP_CLIENT = HttpClientBuilder.create().build();
  private static final ResponseParser ANY_RESPONSE_PARSER = new NoOpResponseParser();

  @Test
  public void providesHttpClientToClient() {
    try (LBHttpSolrClient createdClient =
        new Builder().withBaseSolrUrl(ANY_BASE_SOLR_URL).withHttpClient(ANY_HTTP_CLIENT).build()) {
      assertTrue(createdClient.getHttpClient().equals(ANY_HTTP_CLIENT));
    }
  }

  @Test
  public void providesResponseParserToClient() {
    try (LBHttpSolrClient createdClient =
        new Builder()
            .withBaseSolrUrl(ANY_BASE_SOLR_URL)
            .withResponseParser(ANY_RESPONSE_PARSER)
            .build()) {
      assertTrue(createdClient.getParser().equals(ANY_RESPONSE_PARSER));
    }
  }

  @Test
  public void testDefaultsToBinaryResponseParserWhenNoneProvided() {
    try (LBHttpSolrClient createdClient =
        new Builder().withBaseSolrUrl(ANY_BASE_SOLR_URL).build()) {
      final ResponseParser usedParser = createdClient.getParser();

      assertTrue(usedParser instanceof BinaryResponseParser);
    }
  }
}
 /**
  * Key store 类型HttpClient
  *
  * @param keystore keystore
  * @param keyPassword keyPassword
  * @param supportedProtocols supportedProtocols
  * @param timeout timeout
  * @param retryExecutionCount retryExecutionCount
  * @return CloseableHttpClient
  */
 public static CloseableHttpClient createKeyMaterialHttpClient(
     KeyStore keystore,
     String keyPassword,
     String[] supportedProtocols,
     int timeout,
     int retryExecutionCount) {
   try {
     SSLContext sslContext =
         SSLContexts.custom()
             .useSSL()
             .loadKeyMaterial(keystore, keyPassword.toCharArray())
             .build();
     SSLConnectionSocketFactory sf =
         new SSLConnectionSocketFactory(
             sslContext,
             supportedProtocols,
             null,
             SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
     SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
     return HttpClientBuilder.create()
         .setDefaultSocketConfig(socketConfig)
         .setSSLSocketFactory(sf)
         .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
         .build();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (UnrecoverableKeyException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   }
   return null;
 }
 /**
  * @param maxTotal maxTotal
  * @param maxPerRoute maxPerRoute
  * @param timeout timeout
  * @param retryExecutionCount retryExecutionCount
  * @return
  */
 public static CloseableHttpClient createHttpClient(
     int maxTotal, int maxPerRoute, int timeout, int retryExecutionCount) {
   try {
     SSLContext sslContext = SSLContexts.custom().useSSL().build();
     SSLConnectionSocketFactory sf =
         new SSLConnectionSocketFactory(
             sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =
         new PoolingHttpClientConnectionManager();
     poolingHttpClientConnectionManager.setMaxTotal(maxTotal);
     poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute);
     SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
     poolingHttpClientConnectionManager.setDefaultSocketConfig(socketConfig);
     return HttpClientBuilder.create()
         .setConnectionManager(poolingHttpClientConnectionManager)
         .setSSLSocketFactory(sf)
         .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
         .build();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
   return null;
 }
  public void testMojoExecution() throws Exception {
    assertNotNull(mojo);
    mojo.execute();

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

    HttpGet get = new HttpGet("http://localhost:" + elasticsearchNode.getHttpPort());

    final int connectionTimeout = 500; // millis
    RequestConfig requestConfig =
        RequestConfig.custom()
            .setConnectionRequestTimeout(connectionTimeout)
            .setConnectTimeout(connectionTimeout)
            .setSocketTimeout(connectionTimeout)
            .build();
    get.setConfig(requestConfig);

    try {
      client.execute(get);

      fail("The ES cluster should have been down by now");
    } catch (HttpHostConnectException | ConnectTimeoutException expected) {
    }

    assertTrue(elasticsearchNode.isClosed());
  }
Beispiel #30
0
  protected HttpClient getClient() {
    Credentials defaultcreds = new UsernamePasswordCredentials(this.token, "x");
    CredentialsProvider cp = new BasicCredentialsProvider();
    cp.setCredentials(new AuthScope(getHost(), -1, AuthScope.ANY_REALM), defaultcreds);
    HttpClientBuilder clientBuilder =
        HttpClients.custom()
            .setDefaultCredentialsProvider(cp)
            .setRedirectStrategy(new LaxRedirectStrategy());

    ProxyConfiguration proxy = Hudson.getInstance().proxy;
    if (proxy != null) {
      clientBuilder.setProxy(new HttpHost(proxy.name, proxy.port));
    }

    return clientBuilder.build();
  }