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

The following examples show how to use org.apache.http.impl.client.CloseableHttpClient. 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 check out the related API usage on the sidebar.
Example #1
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 8 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 #2
Source File: HttpUtils.java    From DataLink with Apache License 2.0 7 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 #3
Source File: PipelineTest.java    From JerryMouse with 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 #4
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
@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 #5
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
@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 #6
Source File: HttpUtils.java    From we-cmdb with 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 #7
Source File: HttpClient4Utils.java    From ZTuoExchange_framework with 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 #8
Source File: AbstractUnitTest.java    From deprecated-security-ssl with 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 #9
Source File: ServerLifeCycleTest.java    From JerryMouse with 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 #10
Source File: JunitExistingRestTest.java    From performance-tests with 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 #11
Source File: HttpClientHelper.java    From tiktok4j with 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 #12
Source File: TikTok4jTikTokImpl.java    From tiktok4j with 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 #13
Source File: Qbittorrent.java    From BoxHelper with 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 #14
Source File: HttpUtil.java    From pacbot with 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 #15
Source File: CloudfrontAuthorizedHTMLContentDistributionRule.java    From pacbot with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: NexusArtifactClient.java    From cubeai with 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 #17
Source File: HttpUtil.java    From pacbot with 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 #18
Source File: CommonService.java    From WeEvent with 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 #19
Source File: HttpUtil.java    From anyline with 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
Source File: HttpComponentsClientHttpRequestFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 File: Qbittorrent.java    From BoxHelper with 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 File: SKFSClient.java    From fido2 with 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 File: OpenTSDBReporterTest.java    From metrics with 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 File: ApacheHttpClient.java    From xian with 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 File: InfluxDBReporterTest.java    From metrics with 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
Source File: PreCompressedResourceTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@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 File: ReportDownloadUtil.java    From sailfish-core with 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 File: HttpEventPublisher.java    From DataflowTemplates with 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 File: HttpServiceClient.java    From binlake with 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
Source File: CommentsRestClient.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
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;
}