Пример #1
1
  private HttpClient getClient() {
    if (client == null) {
      HttpClientBuilder clientBuilder = HttpClients.custom();
      RequestConfig.Builder configBuilder = RequestConfig.custom();
      if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        isUsingProxy = true;
        InetSocketAddress adr = (InetSocketAddress) proxy.address();
        clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
      }
      if (timeout != null) {
        configBuilder.setConnectTimeout(timeout.intValue());
      }
      if (readTimeout != null) {
        configBuilder.setSocketTimeout(readTimeout.intValue());
      }
      if (followRedirects != null) {
        configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
      }
      if (hostnameverifier != null) {
        SSLConnectionSocketFactory sslConnectionFactory =
            new SSLConnectionSocketFactory(getSSLContext(), hostnameverifier);
        clientBuilder.setSSLSocketFactory(sslConnectionFactory);
        Registry<ConnectionSocketFactory> registry =
            RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .build();
        clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
      }
      clientBuilder.setDefaultRequestConfig(configBuilder.build());
      client = clientBuilder.build();
    }

    return client;
  }
Пример #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;
  }
Пример #6
0
  @Override
  public ProtocolResponse getProtocolOutput(String url, Metadata md) throws Exception {

    LOG.debug("HTTP connection manager stats {}", CONNECTION_MANAGER.getTotalStats());

    HttpGet httpget = new HttpGet(url);
    httpget.setConfig(requestConfig);

    if (md != null) {
      String ifModifiedSince = md.getFirstValue("cachedLastModified");
      if (StringUtils.isNotBlank(ifModifiedSince)) {
        httpget.addHeader("If-Modified-Since", ifModifiedSince);
      }

      String ifNoneMatch = md.getFirstValue("cachedEtag");
      if (StringUtils.isNotBlank(ifNoneMatch)) {
        httpget.addHeader("If-None-Match", ifNoneMatch);
      }
    }

    // no need to release the connection explicitly as this is handled
    // automatically. The client itself must be closed though.
    try (CloseableHttpClient httpclient = builder.build()) {
      return httpclient.execute(httpget, this);
    }
  }
Пример #7
0
  private CloseableHttpClient generateClient(Site site) {
    HttpClientBuilder httpClientBuilder =
        HttpClients.custom().setConnectionManager(connectionManager);
    if (site != null && site.getUserAgent() != null) {
      httpClientBuilder.setUserAgent(site.getUserAgent());
    } else {
      httpClientBuilder.setUserAgent("");
    }
    if (site == null || site.isUseGzip()) {
      httpClientBuilder.addInterceptorFirst(
          new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
              if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
              }
            }
          });
    }
    SocketConfig socketConfig =
        SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    if (site != null) {
      httpClientBuilder.setRetryHandler(
          new DefaultHttpRequestRetryHandler(site.getRetryTimes(), true));
    }
    generateCookie(httpClientBuilder, site);
    return httpClientBuilder.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);
    }
  }
Пример #9
0
 /** 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();
   }
 }
Пример #10
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());
 }
Пример #11
0
  @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();
  }
Пример #12
0
  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());
  }
Пример #13
0
  /** 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();
      }
    }
  }
 /** 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
       }
     }
   }
 }
Пример #15
0
 private static CloseableHttpClient buildHttpClient(boolean isMultiThread) {
   HttpClientBuilder httpClientBuilder =
       HttpClientBuilder.create().setDefaultRequestConfig(buildRequestConfig());
   if (isMultiThread) {
     httpClientBuilder.setConnectionManager(bulidConnectionManager());
   }
   return httpClientBuilder.build();
 }
Пример #16
0
  private static HttpClient createHttpClient() {
    RequestConfig config =
        RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();

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

    return hcBuilder.build();
  }
Пример #17
0
 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();
   }
 }
Пример #18
0
  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);
    }
  }
Пример #19
0
  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);
  }
  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();
  }
Пример #21
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();
 }
  @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);
  }
Пример #23
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();
  }
  /**
   * Builds the http client.
   *
   * @throws KeyManagementException the key management exception
   * @throws NoSuchAlgorithmException the no such algorithm exception
   */
  private void buildHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    if (this.sslsf == null) {
      this.sslsf = getDefaultSSLSocketFactory();
    }

    HttpClientBuilder httpClientBuilder =
        HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .setSSLSocketFactory(sslsf);

    if (proxy != null) {
      httpClientBuilder.setProxy(proxy);
    }

    httpClient = httpClientBuilder.build();
  }
 private ActivityClient(String host, int port, int socketTimeout) {
   RequestConfig.Builder requestBuilder = RequestConfig.custom();
   requestBuilder = requestBuilder.setConnectTimeout(socketTimeout);
   requestBuilder = requestBuilder.setConnectionRequestTimeout(socketTimeout);
   requestBuilder = requestBuilder.setSocketTimeout(socketTimeout);
   HttpClientBuilder builder = HttpClientBuilder.create();
   builder.setDefaultRequestConfig(requestBuilder.build());
   httpClient = builder.build();
   this.connectionUrl = "http://" + host + ":" + port + "/connection";
   this.queryUrl = "http://" + host + ":" + port + "/query";
   this.preparedStatementExecutionUrl =
       "http://" + host + ":" + port + "/prepared-statement-execution";
   this.batchUrl = "http://" + host + ":" + port + "/batch-execution";
   this.preparedStatementPreparationUrl =
       "http://" + host + ":" + port + "/prepared-statement-preparation";
 }
  public static void download(
      Session session, OutputStream os, String URL, FileProgressCallback callback)
      throws Exception {

    HttpClientBuilder clientBuilder = HttpUtil.getClientBuilder(session);
    HttpGetHC4 request = HttpUtil.getHttpGet(session, URL);

    HttpResponse response = clientBuilder.build().execute(request);
    HttpUtil.checkStatusCode(request, response);
    InputStream is = response.getEntity().getContent();

    try {
      transfer(request, is, os, callback);
    } finally {
      close(is);
    }
  }
  @Override
  public synchronized HttpClient getHttpClient() {
    if (myHttpClient == null) {

      PoolingHttpClientConnectionManager connectionManager =
          new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);

      // @formatter:off
      RequestConfig defaultRequestConfig =
          RequestConfig.custom()
              .setSocketTimeout(mySocketTimeout)
              .setConnectTimeout(myConnectTimeout)
              .setConnectionRequestTimeout(myConnectionRequestTimeout)
              .setStaleConnectionCheckEnabled(true)
              .setProxy(myProxy)
              .build();

      HttpClientBuilder builder =
          HttpClients.custom()
              .setConnectionManager(connectionManager)
              .setDefaultRequestConfig(defaultRequestConfig)
              .disableCookieManagement();

      if (myProxy != null
          && StringUtils.isNotBlank(myProxyUsername)
          && StringUtils.isNotBlank(myProxyPassword)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope(myProxy.getHostName(), myProxy.getPort()),
            new UsernamePasswordCredentials(myProxyUsername, myProxyPassword));
        builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        builder.setDefaultCredentialsProvider(credsProvider);
      }

      myHttpClient = builder.build();
      // @formatter:on

    }

    return myHttpClient;
  }
Пример #28
0
  public static void performHTTPRequest(String url) {
    try {
      HttpGet getMethod = new HttpGet(url);
      HttpClientBuilder clientBuilder = HttpClientBuilder.create();

      String[] userPassword = url.split("@")[0].replace("http://", "").split(":");

      CredentialsProvider credsProvider = new BasicCredentialsProvider();
      credsProvider.setCredentials(
          new AuthScope(getMethod.getURI().getHost(), getMethod.getURI().getPort()),
          new UsernamePasswordCredentials(userPassword[0], userPassword[1]));
      clientBuilder.setDefaultCredentialsProvider(credsProvider);
      HttpClient httpClient = clientBuilder.build();

      httpClient.execute(getMethod);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #29
0
  public static Map<String, Object> doPostToWx(String url, String outstr) {

    // 创建HttpClientBuilder
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    // HttpClient
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

    HttpPost httpPost = new HttpPost(url);

    Map<String, Object> rtnMap = null;
    try {
      httpPost.setEntity(new StringEntity(outstr, "UTF-8"));
      HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
      // 获取响应消息实体
      HttpEntity entity = httpResponse.getEntity();
      // 响应状态
      logger.debug("status:{}", httpResponse.getStatusLine());
      // 判断响应实体是否为空
      if (entity != null) {
        logger.debug("contentEncoding:" + entity.getContentEncoding());
        String responseStr = EntityUtils.toString(entity, "UTF-8");
        logger.debug("response content\n", responseStr);

        rtnMap = JsonUtil.fromJson(responseStr, Map.class);

        logger.debug("返回的Map:\n{}", rtnMap);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        // 关闭流并释放资源
        closeableHttpClient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return rtnMap;
  }
Пример #30
0
  @BeforeClass
  public static void beforeClass() throws Exception {
    ourPort = PortUtil.findFreePort();
    ourServer = new Server(ourPort);
    ourCtx = new FhirContext(Patient.class);

    ourProvider = new DummyProvider();

    ServletHandler proxyHandler = new ServletHandler();
    RestfulServer servlet = new RestfulServer(ourCtx);
    servlet.setPlainProviders(ourProvider);
    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();
  }