Java Code Examples for org.apache.http.impl.client.CloseableHttpClient

The following examples show how to use org.apache.http.impl.client.CloseableHttpClient. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: JerryMouse   Source File: PipelineTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testContentLengthOutBound() throws Exception {
    int availablePort = NetUtils.getAvailablePort();
    HttpServer httpSever = new HttpServer("/tmp/static");
    List<Context> contexts = httpSever.getContexts();
    Context context = contexts.get(0);
    context.setPort(availablePort);
    context.init();
    context.start();
    ServletContext servletContext = context.getServletContext();
    BoundPipeline rootBoundPipeline = new RootBoundPipeline(servletContext);
    BoundPipeline contentOutBoundPipeline = new TestContentOutBoundPipeline(servletContext);
    rootBoundPipeline.setNext(contentOutBoundPipeline);
    servletContext.setOutboundPipeline(rootBoundPipeline);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost:" + availablePort + "/hello");
    CloseableHttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    String responseStr = EntityUtils.toString(entity);
    assertEquals("hel", responseStr);
}
 
Example 2
@Test
public void checkVersionSpecificUpdateCenterTest() throws Exception {
    //Test where version specific update center exists
    pm.setJenkinsVersion(new VersionNumber("2.176"));

    mockStatic(HttpClients.class);
    CloseableHttpClient httpclient = mock(CloseableHttpClient.class);

    when(HttpClients.createSystem()).thenReturn(httpclient);
    HttpHead httphead = mock(HttpHead.class);

    whenNew(HttpHead.class).withAnyArguments().thenReturn(httphead);
    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(httpclient.execute(httphead)).thenReturn(response);

    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);

    int statusCode = HttpStatus.SC_OK;
    when(statusLine.getStatusCode()).thenReturn(statusCode);

    pm.checkAndSetLatestUpdateCenter();

    String expected = dirName(cfg.getJenkinsUc()) + pm.getJenkinsVersion() + Settings.DEFAULT_UPDATE_CENTER_FILENAME;
    assertEquals(expected, pm.getJenkinsUCLatest());
}
 
Example 3
@Test
public void checkVersionSpecificUpdateCenterBadRequestTest() throws Exception {
    pm.setJenkinsVersion(new VersionNumber("2.176"));

    mockStatic(HttpClients.class);
    CloseableHttpClient httpclient = mock(CloseableHttpClient.class);

    when(HttpClients.createSystem()).thenReturn(httpclient);
    HttpHead httphead = mock(HttpHead.class);

    whenNew(HttpHead.class).withAnyArguments().thenReturn(httphead);
    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(httpclient.execute(httphead)).thenReturn(response);

    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);

    int statusCode = HttpStatus.SC_BAD_REQUEST;
    when(statusLine.getStatusCode()).thenReturn(statusCode);

    pm.checkAndSetLatestUpdateCenter();
    String expected = cfg.getJenkinsUc().toString();
    assertEquals(expected, pm.getJenkinsUCLatest());
}
 
Example 4
Source Project: cubeai   Source File: NexusArtifactClient.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source Project: we-cmdb   Source File: HttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get请求
 *
 * @param msgs
 * @param url
 * @return
 * @throws ClientProtocolException
 * @throws UnknownHostException
 * @throws IOException
 */
public static String get(Map<String, Object> msgs, String url)
        throws ClientProtocolException, UnknownHostException, IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
        if (null != msgs) {
            for (Entry<String, Object> entry : msgs.entrySet()) {
                if (entry.getValue() != null) {
                    valuePairs.add(new BasicNameValuePair(entry.getKey(),
                            entry.getValue().toString()));
                }
            }
        }
        // EntityUtils.toString(new UrlEncodedFormEntity(valuePairs),
        // CHARSET);
        url = url + "?" + URLEncodedUtils.format(valuePairs, CHARSET_UTF_8);
        HttpGet request = new HttpGet(url);
        CloseableHttpResponse resp = httpClient.execute(request);
        return EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
    } finally {
        httpClient.close();
    }
}
 
Example 6
Source Project: ZTuoExchange_framework   Source File: HttpClient4Utils.java    License: MIT License 6 votes vote down vote up
/**
 * 实例化HttpClient
 *
 * @param maxTotal
 * @param maxPerRoute
 * @param socketTimeout
 * @param connectTimeout
 * @param connectionRequestTimeout
 * @return
 */
public static HttpClient createHttpClient(int maxTotal, int maxPerRoute, int socketTimeout, int connectTimeout,
                                          int connectionRequestTimeout) {
    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(maxTotal);
    cm.setDefaultMaxPerRoute(maxPerRoute);
    cm.setValidateAfterInactivity(200); // 一个连接idle超过200ms,再次被使用之前,需要先做validation
    CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(cm)
            .setConnectionTimeToLive(30, TimeUnit.SECONDS)
            .setRetryHandler(new StandardHttpRequestRetryHandler(3, true)) // 配置出错重试
            .setDefaultRequestConfig(defaultRequestConfig).build();

    startMonitorThread(cm);

    return httpClient;
}
 
Example 7
Source Project: deprecated-security-ssl   Source File: AbstractUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
protected String executeSimpleRequest(final String request) throws Exception {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = getHTTPClient();
            response = httpClient.execute(new HttpGet(getHttpServerUri() + "/" + request));

            if (response.getStatusLine().getStatusCode() >= 300) {
                throw new Exception("Statuscode " + response.getStatusLine().getStatusCode()+" - "+response.getStatusLine().getReasonPhrase()+ "-" +IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
            }

            return IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
        } finally {

            if (response != null) {
                response.close();
            }

            if (httpClient != null) {
                httpClient.close();
            }
        }
    }
 
Example 8
Source Project: JerryMouse   Source File: ServerLifeCycleTest.java    License: MIT License 6 votes vote down vote up
@Test(expected = HttpHostConnectException.class)
public void testServerStartAndStop() throws Exception {
    int availablePort = NetUtils.getAvailablePort();
    HttpServer httpSever = new HttpServer("/tmp/static");
    List<Context> contexts = httpSever.getContexts();
    Context context = contexts.get(0);
    context.setPort(availablePort);
    httpSever.start();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost:" + availablePort + "/");
    CloseableHttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    String responseStr = EntityUtils.toString(entity);
    assertEquals("/", responseStr);
    httpSever.destroy();
    httpclient.execute(httpget);
}
 
Example 9
Source Project: performance-tests   Source File: JunitExistingRestTest.java    License: MIT License 6 votes vote down vote up
/**
 * This test sometimes failed due to GitHub rate limiting settings.
 * The failures should be captured in the reports(CSV and html).
 * This is knowing kept here to test the rate limiting and show
 * how a failed test can be tracked in the log/reports
 */
@Test
public void testGitHubGetApi() throws IOException, InterruptedException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet request = new HttpGet("https://api.github.com//users/octocat");

    // - - - - - - - - - - - - - - - - - - - - - - - - -
    // Add known delay to reflect "responseDelay" value
    // in the CSV report at least more than this number.
    // - - - - - - - - - - - - - - - - - - - - - - - - -
    Thread.sleep(1000);

    HttpResponse response = httpClient.execute(request);
    final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    System.out.println("### response: \n" + responseBodyActual);

    assertThat(response.getStatusLine().getStatusCode(), CoreMatchers.is(200));
    assertThat(responseBodyActual, CoreMatchers.containsString("\"login\":\"octocat\""));

}
 
Example 10
Source Project: tiktok4j   Source File: HttpClientHelper.java    License: MIT License 6 votes vote down vote up
/**
 * Get HTTP response.
 *
 * @param url
 * @return
 */
public static JsonNode getHttpResponse(String url) {
	try {
		LogHelper.debug("Get : " + url);
		HttpGet httpGet = new HttpGet(url);
		httpGet.setHeader("User-Agent", Configurations.HTTP_CLIENT_USER_AGENT);
		try (CloseableHttpClient client = HttpClientBuilder.create().build();
				CloseableHttpResponse response = client.execute(httpGet)) {
			LogHelper.debug(response);
			LogHelper.debug("code = " + response.getStatusLine().getStatusCode());
			String responseString = EntityUtils.toString(response.getEntity());
			LogHelper.debug("response = " + responseString);
			return JsonHelper.getObjectMapper().readTree(responseString);
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 11
Source Project: tiktok4j   Source File: TikTok4jTikTokImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Get HTTP response.
 *
 * @param url
 * @return
 */
private static JsonNode getHttpResponseAsJson(String url) {
	try {
		LogHelper.debug("Get : " + url);
		HttpGet httpGet = new HttpGet(url);
		httpGet.setHeader("Host", UrlHelper.getHostname(url));
		httpGet.setHeader("X-SS-TC", "0");
		httpGet.setHeader("User-Agent", USER_AGENT);
		httpGet.setHeader("Accept-Encoding", "gzip");
		httpGet.setHeader("Connection", "keep-alive");
		httpGet.setHeader("X-Tt-Token", "");
		httpGet.setHeader("sdk-version", "1");
		httpGet.setHeader("Cookie", "");

		try (CloseableHttpClient client = HttpClientBuilder.create().build();
				CloseableHttpResponse response = client.execute(httpGet)) {
			LogHelper.debug(response);
			LogHelper.debug("code = " + response.getStatusLine().getStatusCode());
			String responseString = EntityUtils.toString(response.getEntity());
			LogHelper.debug("response = " + responseString);
			return JsonHelper.getObjectMapper().readTree(responseString);
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 12
Source Project: BoxHelper   Source File: Qbittorrent.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean removeTorrent(String link, String name) throws IOException {
    if (link == null || "".equals(link) || name == null || "".equals(name)) return true;
    System.out.println("\u001b[37;1m [Info]   \u001b[36m  qBittorrent:\u001b[0m Removing torrent " + name + " ...");
    String hash = null;
    Long size = 0L;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    for (Object torrent: this.allTorrents){
        if (((QbittorrentTorrents) torrent).getName().contains(name) || ((QbittorrentTorrents) torrent).getName().contains(name.replaceAll("\\s", "\\."))){
            hash = ((QbittorrentTorrents) torrent).getHash();
            size = ((QbittorrentTorrents) torrent).getTotal_size();
            break;
        }
    }
    HttpGet httpget = new HttpGet("http://127.0.0.1:" + getPort() + "/api/v2/torrents/delete?hashes=" + hash + "&deleteFiles=true");
    httpget.addHeader("User-Agent", "BoxHelper");
    httpget.addHeader("Host", "127.0.0.1:" + getPort());
    httpget.addHeader("Cookie", "SID=" + this.sessionID);
    httpClient.execute(httpget);
    boolean removed = recheck(hash, name, size, TorrentState.ALL);
    if (removed) System.out.println("\u001b[33;1m [Warning]\u001b[36m  qBittorrent:\u001b[0m " + name + " did not removed. Retry later...");
    else System.out.println("\u001b[37;1m [Info]   \u001b[36m  qBittorrent:\u001b[0m " + name + " successfully removed.");
    httpClient.close();
    return removed;
}
 
Example 13
Source Project: pacbot   Source File: HttpUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the.
 *
 * @param uri
 *            the uri
 * @return the string
 */
public static String get(String uri ,String bearerToken) throws Exception  {
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("content-type", "application/json");
    httpGet.addHeader("cache-control", "no-cache");
    if(!Strings.isNullOrEmpty(bearerToken)){
        httpGet.addHeader("Authorization", "Bearer "+bearerToken);
    }
    CloseableHttpClient httpClient = getHttpClient();
    if(httpClient!=null){
        HttpResponse httpResponse;
        try {
           
            httpResponse = httpClient.execute(httpGet);
            if( httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_UNAUTHORIZED){
                throw new UnAuthorisedException();
            }
            return EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
            LOGGER.error("Error getting the data " , e);
            throw e;
        }
    }
    return "{}";
}
 
Example 14
public boolean isWebSiteHosted(String url) throws Exception {
	HttpGet httpGet = new HttpGet(url);
	httpGet.addHeader("content-type", "text/html");
	CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	if (httpClient != null) {
		HttpResponse httpResponse;
		try {
			httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() >= 400) {
				return false;
			}
		} catch (Exception e) {
			logger.error("Exception getting from url  :[{}],[{}] ", url, e.getMessage());
			throw e;
		}
	}
	return true;
}
 
Example 15
Source Project: cubeai   Source File: NexusArtifactClient.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 16
Source Project: pacbot   Source File: HttpUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String httpGetMethodWithHeaders(String url,Map<String, Object> headers) throws Exception {
    String json = null;
    
    HttpGet get = new HttpGet(url);
    CloseableHttpClient httpClient = null;
    if (headers != null && !headers.isEmpty()) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            get.setHeader(entry.getKey(), entry.getValue().toString());
        }
    }
    try {
        httpClient = getHttpClient();
        CloseableHttpResponse res = httpClient.execute(get);
        if (res.getStatusLine().getStatusCode() == 200) {
            json = EntityUtils.toString(res.getEntity());
        }
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
    return json;
}
 
Example 17
Source Project: WeEvent   Source File: CommonService.java    License: Apache License 2.0 6 votes vote down vote up
public CloseableHttpResponse getCloseResponse(HttpServletRequest req, String newUrl, String jsonString) throws ServletException {
    CloseableHttpResponse closeResponse;
    try {
        log.info("url {}", newUrl);
        CloseableHttpClient client = this.generateHttpClient();
        if (req.getMethod().equals(METHOD_TYPE)) {
            HttpGet get = this.getMethod(newUrl, req);
            closeResponse = client.execute(get);
        } else {
            HttpPost postMethod = this.postMethod(newUrl, req, jsonString);
            closeResponse = client.execute(postMethod);
        }
    } catch (Exception e) {
        log.error("getCloseResponse fail,error:{}", e.getMessage());
        throw new ServletException(e.getMessage());
    }
    return closeResponse;
}
 
Example 18
Source Project: DataLink   Source File: HttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 执行一个HTTP GET请求,返回请求响应的HTML
 *
 * @param url 请求的URL地址
 * @return 返回请求响应的HTML
 * @throws IOException
 */
public static String doGet(String url, Map<String, String> params) throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    if(params!=null && params.size()>0) {
        url = url + "?" + map2Str(params);
    }
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse httpResponse = client.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity, "utf-8");
        }
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return "";
}
 
Example 19
Source Project: anyline   Source File: HttpUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static HttpResult put(CloseableHttpClient client, Map<String, String> headers, String url, String encode,  List<HttpEntity> entitys) { 
	if(null == client){ 
		if(url.contains("https://")){ 
			client = defaultSSLClient(); 
		}else{ 
			client =  defaultClient(); 
		} 
	} 
	if(url.startsWith("//")){ 
		url = "http:" + url; 
	} 
	HttpResult result = new HttpResult(); 
	HttpPut method = new HttpPut(url); 
	if(null != entitys){ 
		for(HttpEntity entity:entitys){ 
			method.setEntity(entity); 
		} 
	} 
	setHeader(method, headers); 
	result = exe(client, method, encode); 
	return result; 
}
 
Example 20
@Test
public void mergeBasedOnCurrentHttpClient() throws Exception {
	RequestConfig defaultConfig = RequestConfig.custom()
			.setSocketTimeout(1234).build();
	final CloseableHttpClient client = mock(CloseableHttpClient.class,
			withSettings().extraInterfaces(Configurable.class));
	Configurable configurable = (Configurable) client;
	given(configurable.getConfig()).willReturn(defaultConfig);

	HttpComponentsClientHttpRequestFactory hrf = new HttpComponentsClientHttpRequestFactory() {
		@Override
		public HttpClient getHttpClient() {
			return client;
		}
	};
	hrf.setReadTimeout(5000);

	RequestConfig requestConfig = retrieveRequestConfig(hrf);
	assertEquals(-1, requestConfig.getConnectTimeout());
	assertEquals(-1, requestConfig.getConnectionRequestTimeout());
	assertEquals(5000, requestConfig.getSocketTimeout());

	// Update the Http client so that it returns an updated  config
	RequestConfig updatedDefaultConfig = RequestConfig.custom()
			.setConnectTimeout(1234).build();
	given(configurable.getConfig()).willReturn(updatedDefaultConfig);
	hrf.setReadTimeout(7000);
	RequestConfig requestConfig2 = retrieveRequestConfig(hrf);
	assertEquals(1234, requestConfig2.getConnectTimeout());
	assertEquals(-1, requestConfig2.getConnectionRequestTimeout());
	assertEquals(7000, requestConfig2.getSocketTimeout());
}
 
Example 21
Source Project: BoxHelper   Source File: Qbittorrent.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void acquireGlobalInfo() throws IOException {
    System.out.println("\u001b[37;1m [Info]   \u001b[36m  qBittorrent:\u001b[0m Acquiring global status ...");
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://127.0.0.1:" + this.getPort() + "/api/v2/transfer/info");
    httpget.addHeader("User-Agent", "BoxHelper");
    httpget.addHeader("Host", "127.0.0.1:" + this.getPort());
    httpget.addHeader("Cookie", "SID=" + this.sessionID);
    CloseableHttpResponse response = httpClient.execute(httpget);
    String responseString = "";
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        responseString = EntityUtils.toString(entity) ;
        Gson gson = new Gson();
        QbittorrentGlobalInfo qbittorrentGlobalInfo = gson.fromJson(responseString, QbittorrentGlobalInfo.class);
        this.setDownloadSpeed(qbittorrentGlobalInfo.getDl_info_speed());
        this.setUploadSpeed(qbittorrentGlobalInfo.getUp_info_speed());
        if (this.getCount() ==1) {
            this.setAverageUp(this.getUploadSpeed());
            this.setAverageDown(this.getDownloadSpeed());
        }
        else {
            this.setAverageUp((this.getAverageUp() * (this.getCount() - 1) + this.getUploadSpeed()) / this.getCount());
            this.setAverageDown((this.getAverageDown() * (this.getCount() - 1) + this.getDownloadSpeed()) / this.getCount());
        }
        acquireTorrents(TorrentState.ALL);
        this.allTorrents.forEach(torrent -> {
            this.setTorrentSize(this.getTorrentSize() + ((QbittorrentTorrents) torrent).getTotal_size());
        });
        System.out.println("\u001b[37;1m [Info]   \u001b[36m  qBittorrent:\u001b[0m Current upload speed is \u001b[33m" +
                new DecimalFormat("#0.00").format(this.getUploadSpeed() / (double)1048576) + " MB/s\u001b[0m (Avg. " +
                new DecimalFormat("#0.00").format(this.getAverageUp() / (double)1048576) + " MB/s) .");
    } else System.out.println("\u001b[33;1m [Warning]\u001b[36m  qBittorrent:\u001b[0m Cannot acquire global status.");
    response.close();
    httpClient.close();

    checkIO();
}
 
Example 22
Source Project: fido2   Source File: SKFSClient.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String callServer(HttpRequestBase request){
    try(CloseableHttpClient httpclient = HttpClients.createDefault()){
        HttpResponse response = httpclient.execute(request);
        return getAndVerifySuccessfulResponse(response);
    }
    catch (IOException ex) {
        POCLogger.logp(Level.SEVERE, CLASSNAME, "callSKFSRestApi", "POC-ERR-5001", ex.getLocalizedMessage());
        throw new WebServiceException(POCLogger.getMessageProperty("POC-ERR-5001"));
    }
}
 
Example 23
Source Project: metrics   Source File: OpenTSDBReporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReporting(@Mocked CloseableHttpClient httpClient,
    @Mocked CloseableHttpResponse closeableHttpResponse,
    @Mocked StatusLine statusLine)
    throws InterruptedException, IOException {
  new Expectations() {{
    httpClient.execute((HttpUriRequest) any);
    result = closeableHttpResponse;
    closeableHttpResponse.getStatusLine();
    result = statusLine;
    statusLine.getStatusCode();
    result = 200;
  }};

  MetricRegistry registry = new MetricRegistry();
  OpenTSDBReporter reporter = makeReporter();
  registry.addReporter(reporter);

  Counter counter = registry.counter("counter");
  counter.inc("tag", "value");

  Thread.sleep(3000);

  new Verifications() {{
    HttpUriRequest request;
    httpClient.execute(request = withCapture());
    assertEquals("/api/v1/put", request.getURI().getPath());
    times = 1;
  }};
}
 
Example 24
Source Project: xian   Source File: ApacheHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    if (client != null)
        ((CloseableHttpClient) client).close();
    else
        LOG.warn("客户端对象client是null,你关个毛线!");
}
 
Example 25
Source Project: metrics   Source File: InfluxDBReporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReporting(@Mocked CloseableHttpClient httpClient,
    @Mocked CloseableHttpResponse closeableHttpResponse, @Mocked StatusLine statusLine)
    throws InterruptedException, IOException {
  new Expectations() {{
    httpClient.execute((HttpUriRequest) any);
    result = closeableHttpResponse;
    closeableHttpResponse.getStatusLine();
    result = statusLine;
    statusLine.getStatusCode();
    result = 200;
  }};

  MetricRegistry registry = new MetricRegistry();
  InfluxDBReporter reporter = InfluxDBReporter.builder()
      .withBaseUri(URI.create("http://localhost:8086"))
      .withDatabase("test")
      .build();
  registry.addReporter(reporter);

  Counter counter = registry.counter("counter");
  counter.inc("tag", "value");

  Thread.sleep(3000);

  new Verifications() {{
    httpClient.execute((HttpUriRequest) any);
    times = 1;
  }};
}
 
Example 26
@Test
public void testContentEncodedResource() throws IOException, URISyntaxException {
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

    try (CloseableHttpClient compClient = HttpClientBuilder.create().build()){
        DefaultServer.setRootHandler(new CanonicalPathHandler()
                .setNext(new PathHandler()
                        .addPrefixPath("/path", new ResourceHandler(new PreCompressedResourceSupplier(new PathResourceManager(rootPath, 10485760)).addEncoding("gzip", ".gz"))
                                .setDirectoryListingEnabled(true))));

        //assert response without compression
        final String plainResponse = assertResponse(client.execute(get), false);

        //assert compressed response, that doesn't exists, so returns plain
        assertResponse(compClient.execute(get), false, plainResponse);

        //generate compressed resource with extension .gz
        generatePreCompressedResource("gz");

        //assert compressed response that was pre compressed
        assertResponse(compClient.execute(get), true, plainResponse, "gz");

    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example 27
Source Project: sailfish-core   Source File: ReportDownloadUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static File download(URL reportLink, Function<String, File> fileProvider) {

        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpGet get = new HttpGet(reportLink.toURI());
            return httpclient.execute(get, response -> {
                String attachmentName = DEFAULT_REPORT_NAME_ZIP;

                Header header = response.getFirstHeader(HttpHeaders.CONTENT_DISPOSITION);
                if (header != null) {
                    for (HeaderElement headerElement : header.getElements()) {
                        NameValuePair parameter = headerElement.getParameterByName(FILENAME_HEADER_PARAM);
                        if (parameter != null) {
                            attachmentName = ObjectUtils.defaultIfNull(parameter.getValue(), UUID.randomUUID().toString());
                            break;
                        }
                    }
                }
                File zipTarget = fileProvider.apply(attachmentName);
                if (zipTarget.length() != response.getEntity().getContentLength()) {
                    FileUtils.copyInputStreamToFile(response.getEntity().getContent(), zipTarget);
                }
                return zipTarget;
            });
        } catch (Exception e) {
            throw new EPSCommonException("Unable to download report by specified link - " + reportLink, e);
        }
    }
 
Example 28
Source Project: DataflowTemplates   Source File: HttpEventPublisher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Validates and builds a {@link HttpEventPublisher} object.
 *
 * @return {@link HttpEventPublisher}
 */
public HttpEventPublisher build()
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  checkNotNull(token(), "Authentication token needs to be specified via withToken(token).");
  checkNotNull(genericUrl(), "URL needs to be specified via withUrl(url).");

  if (disableCertificateValidation() == null) {
    LOG.info("Certificate validation disabled: {}", DEFAULT_DISABLE_CERTIFICATE_VALIDATION);
    setDisableCertificateValidation(DEFAULT_DISABLE_CERTIFICATE_VALIDATION);
  }

  if (maxElapsedMillis() == null) {
    LOG.info(
        "Defaulting max backoff time to: {} milliseconds ",
        ExponentialBackOff.DEFAULT_MAX_ELAPSED_TIME_MILLIS);
    setMaxElapsedMillis(ExponentialBackOff.DEFAULT_MAX_ELAPSED_TIME_MILLIS);
  }

  CloseableHttpClient httpClient =
      getHttpClient(DEFAULT_MAX_CONNECTIONS, disableCertificateValidation());

  setTransport(new ApacheHttpTransport(httpClient));
  setRequestFactory(transport().createRequestFactory());

  return autoBuild();
}
 
Example 29
Source Project: binlake   Source File: HttpServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * execute http entity
 *
 * @param entity: http entity
 * @param url
 * @return
 * @throws Exception
 */
private <V> V execute(HttpEntity entity, String url, RunCallUtils<byte[], V> call, Callable<V> fail) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);

        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        CloseableHttpResponse resp = client.execute(httpPost);

        if (resp == null) {
            LogUtils.warn.warn("no response from server " + url);
            return fail.call();
        }

        int c = resp.getStatusLine().getStatusCode();
        if (c != 200) {
            LogUtils.warn.warn("response status code from server " + c);
            return fail.call();
        }

        return call.call(IOUtils.readFully(resp.getEntity().getContent(), -1, false));
    } finally {
        client.close();
    }
}
 
Example 30
private String doPostLogin(String username, String password) throws Exception {
	
	CloseableHttpClient httpclient = getHTTPClient(username, password);

	List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	formparams.add(new BasicNameValuePair("username", username));
	formparams.add(new BasicNameValuePair("password", password));
	
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
	
	HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/auth/login");
	httppost.setEntity(entity);	

	CloseableHttpResponse response = httpclient.execute(httppost);
	try {
		HttpEntity rent = response.getEntity();
		if (rent != null) {
			String respoBody = EntityUtils.toString(rent, "UTF-8");
			System.out.println(respoBody);
			return respoBody;
		}
	} finally {
		response.close();
	}

	return null;
}
 
Example 31
/**
 * httpclient��ʽ HTTP/HTTPS��ʼ��
 *
 * @param urlParam �������
 * @param cerpath  ����·��
 * @return ����HTTPCLIENT����
 */
private CloseableHttpClient iniHttpClient(String urlParam, String cerpath) throws NoSuchAlgorithmException, KeyManagementException {
    CloseableHttpClient httpclient;
    urlParam = urlParam.trim();
    if (urlParam.startsWith("http://")) {
        httpclient = HttpClients.createDefault();
    } else if (urlParam.startsWith("https://")) {
        //�����ƹ���֤�ķ�ʽ����https����
        SSLContext sslContext;
        if (null == cerpath || "".equals(cerpath.trim())) {
            LogUtil.APP.info("��ʼ����HTTPS������֤����...");
            TrustManager[] trustManagers = {new MyX509TrustManager()};
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());
        } else {
            LogUtil.APP.info("��ʼ����HTTPS˫����֤����...");
            String[] strcerpath = cerpath.split(";", -1);
            HttpClientTools hct = new HttpClientTools();
            sslContext = hct.sslContextKeyStore(strcerpath[0], strcerpath[1]);
        }

        // ����Э��http��https��Ӧ�Ĵ���socket���ӹ����Ķ���
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                // ������SSL���ӻ���֤����֤����Ϣ
                // .register("https", new SSLConnectionSocketFactory(sslContext)).build();
                // ����������֤
                .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        connManager.setDefaultMaxPerRoute(1);
        //�����Զ����httpclient����
        httpclient = HttpClients.custom().setConnectionManager(connManager).build();
    } else {
        httpclient = HttpClients.createDefault();
    }
    return httpclient;
}
 
Example 32
@Test
public void testTooBigAscii() throws IOException {
  String endpoint = TestOnLocalServer.withHttpPath(
      "dodsC/HRRR/analysis/TP.ascii?u-component_of_wind_isobaric&Temperature_isobaric&v-component_of_wind_isobaric");
  try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    HttpGet httpGet = new HttpGet(endpoint);
    HttpResponse response = httpClient.execute(httpGet);
    StatusLine status = response.getStatusLine();
    Assert.assertEquals(status.getStatusCode(), 403);
    HttpEntity entity = response.getEntity();
    Assert.assertEquals(entity.getContentType().getValue(), MediaType.TEXT_PLAIN.toString());
    String responseString = EntityUtils.toString(entity, "UTF-8");
    Assert.assertTrue(responseString.toLowerCase().contains("request too large"));
  }
}
 
Example 33
Source Project: pacbot   Source File: PacmanUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getResponse(Map<String, String> body, String apiGWurl) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    Gson gson = new Gson();
    String bodyString = gson.toJson(body);
    CloseableHttpResponse response = null;
    String result = null;
    int rcode = 0;

    try {
        HttpPost httpPost = new HttpPost(apiGWurl);
        StringEntity entity = new StringEntity(bodyString);
        entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, PacmanRuleConstants.APPLICATION_JSON));
        httpPost.setEntity(entity);
        response = httpClient.execute(httpPost);
        rcode = response.getStatusLine().getStatusCode();
        if (rcode == 200) {
            result = EntityUtils.toString(response.getEntity());

        }
        httpClient.close();
    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new RuleExecutionFailedExeption(e.getMessage());
    }
    return result;

}
 
Example 34
/**
 * 使用post的方式进行网络请求
 * 一般header中会提供一些json或者from的参数
 *
 * @param url     送信网络路径
 * @param params  参数列表,默认为空map,可以为null
 * @param cookies 所携带的cookie列表,默认为空map,可以为null
 * @param header  头信息,默认为空map,可以为null
 * @return 网页的返回值字符串
 */
@Override
public String post(String url, String params, Map<String, String> cookies, Map<String, String> header) {
    cookies = cookies == null ? new HashMap<>(1) : cookies;
    header = header == null ? new HashMap<>(1) : header;
    String response = null;

    try {
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        // 获取domain
        final String domain = httpPost.getURI().getAuthority();

        // 设置cookie
        CookieStore cookieStore;
        if (!cookies.isEmpty()) {
            cookieStore = toCookieStore(domain, cookies, baseCookieStore);
        } else {
            cookieStore = baseCookieStore;
        }

        // 存在参数, 设置参数
        if (params != null && params.trim().length() > 0) {
            StringEntity entity = new StringEntity(params, CHARSET_UTF_8);
            httpPost.setEntity(entity);
        }


        // 添加头信息
        addHeaders(httpPost, header);

        // 发送请求
        CloseableHttpClient httpClient = getHttpClient(cookieStore);
        response = send(httpClient, httpPost);
    } catch (Exception e) {
        throw new DefaultHttpClientException(e);
    }
    return response;
}
 
Example 35
@Test
public void testPemTrust() throws Exception {

    try (TestServer testServer = new TestServer("sslConfigurator/pem/truststore.jks",
            "sslConfigurator/pem/node1-keystore.jks", "secret", false)) {
        Path rootCaPemPath = FileHelper.getAbsoluteFilePathFromClassPath("sslConfigurator/pem/root-ca.pem");

        Assert.assertTrue(rootCaPemPath.toFile().exists());

        Settings settings = Settings.builder()
                .put("prefix.pemtrustedcas_filepath", rootCaPemPath.getFileName().toString())
                .put("prefix.enable_ssl", "true").put("path.home", rootCaPemPath.getParent().toString()).build();
        Path configPath = rootCaPemPath.getParent();

        SettingsBasedSSLConfigurator sbsc = new SettingsBasedSSLConfigurator(settings, configPath, "prefix");

        SSLConfig sslConfig = sbsc.buildSSLConfig();

        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslConfig.toSSLConnectionSocketFactory()).build()) {

            try (CloseableHttpResponse response = httpClient.execute(new HttpGet(testServer.getUri()))) {
                // Success
            }
        }

    }
}
 
Example 36
Source Project: quarkus-http   Source File: SimpleSSLTestCase.java    License: Apache License 2.0 5 votes vote down vote up
private void runTest(int concurrency, HttpHandler handler) throws IOException, InterruptedException {
    DefaultServer.setRootHandler(handler);
    DefaultServer.startSSLServer();
    try (CloseableHttpClient client = HttpClients.custom().disableConnectionState()
            .setSSLContext(DefaultServer.getClientSSLContext())
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(5000).build())
            .setMaxConnPerRoute(1000)
            .build()) {
        ExecutorService executorService = Executors.newFixedThreadPool(concurrency);
        AtomicBoolean failed = new AtomicBoolean();
        Runnable task = new Runnable() {
            @Override
            public void run() {
                if (failed.get()) {
                    return;
                }
                try (CloseableHttpResponse result = client.execute(new HttpGet(DefaultServer.getDefaultServerSSLAddress()))) {
                    Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                    Header[] header = result.getHeaders("scheme");
                    Assert.assertEquals("https", header[0].getValue());
                    EntityUtils.consumeQuietly(result.getEntity());
                } catch (Throwable t) {
                    if (failed.compareAndSet(false, true)) {
                        t.printStackTrace();
                        executorService.shutdownNow();
                    }
                }
            }
        };
        for (int i = 0; i < concurrency * 300; i++) {
            executorService.submit(task);
        }
        executorService.shutdown();
        Assert.assertTrue(executorService.awaitTermination(70, TimeUnit.SECONDS));
        Assert.assertFalse(failed.get());
    } finally {
        DefaultServer.stopSSLServer();
    }
}
 
Example 37
Source Project: warnings-ng-plugin   Source File: RemoteAxivionDashboard.java    License: MIT License 5 votes vote down vote up
@Override
public JsonObject getIssues(final AxIssueKind kind) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    try (CloseableHttpClient client =
                 HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(projectUrl + "/issues?kind=" + kind);
        httpget.addHeader(new BasicHeader("Accept", "application/json"));
        BasicHeader userAgent = new BasicHeader(X_AXIVION_USER_AGENT, API_USER_AGENT);
        httpget.addHeader(userAgent);

        try (CloseableHttpResponse response = client.execute(httpget)) {
            if (response.getStatusLine().getStatusCode() == HTTP_STATUS_OK) {
                return convertToJson(response);
            }
        }

        // dashboard version < 6.9.3 need the fallback header
        httpget.removeHeader(userAgent);
        httpget.addHeader(new BasicHeader(X_AXIVION_USER_AGENT, FALL_USER_AGENT));
        try (CloseableHttpResponse legacyResponse = client.execute(httpget)) {
            return convertToJson(legacyResponse);
        }
    }
    catch (IOException e) {
        throw new ParsingException(e, "Cannot retrieve information from dashboard");
    }
}
 
Example 38
Source Project: api-layer   Source File: HttpClientProxyConfig.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Bean
public CloseableHttpClient httpClientProxy() {
    Enhancer e = new Enhancer();
    e.setSuperclass(CloseableHttpClient.class);
    e.setCallback((MethodInterceptor) (o, method, objects, methodProxy) ->
        {
            if (method.getName().equals("execute") && objects.length > 0 && objects[0] instanceof HttpRequest) {
                serviceAuthenticationDecorator.process((HttpRequest) objects[0]);
            }
            return method.invoke(clientChooser.chooseClient(), objects);
        }
    );
    return (CloseableHttpClient) e.create();
}
 
Example 39
Source Project: DataSphereStudio   Source File: AzkabanProjectService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * delete=boolean
 * project=projectName
 *
 * @param project
 * @param session
 */
@Override
public void deleteProject(Project project, Session session) throws AppJointErrorException {
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("delete", "true"));
    params.add(new BasicNameValuePair("project", project.getName()));
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(session.getCookies()[0]);
    HttpClientContext context = HttpClientContext.create();
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = null;
    try {
        String finalUrl = projectUrl + "?" + EntityUtils.toString(new UrlEncodedFormEntity(params));
        HttpGet httpGet = new HttpGet(finalUrl);
        httpGet.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        response = httpClient.execute(httpGet, context);
        Header[] allHeaders = context.getRequest().getAllHeaders();
        Optional<Header> header = Arrays.stream(allHeaders).filter(f -> "Cookie".equals(f.getName())).findFirst();
        header.ifPresent(DSSExceptionUtils.handling(this::parseCookie));
    } catch (Exception e) {
        logger.error("delete scheduler project failed,reason:",e);
        throw new AppJointErrorException(90010, e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
}
 
Example 40
Source Project: api-layer   Source File: BeanConfig.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Bean
public HttpClientChooser httpClientChooser(@Qualifier("secureHttpClientWithKeystore")
                                               CloseableHttpClient withCertificate,
                                           @Qualifier("secureHttpClientWithoutKeystore")
                                               CloseableHttpClient withoutCertificate
) {
    return new HttpClientChooser(withoutCertificate, withCertificate);
}