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

The following examples show how to use org.apache.http.impl.client.BasicResponseHandler. 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: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 7 votes vote down vote up
public static String[] getHosts() {
	try {
		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
				new UsernamePasswordCredentials("admin", "admin"));
		HttpGet get = new HttpGet("http://" + host_name + ":" + admin_port + "/manage/v2/hosts?format=json");

		HttpResponse response = client.execute(get);
		ResponseHandler<String> handler = new BasicResponseHandler();
		String body = handler.handleResponse(response);
		JsonNode actualObj = new ObjectMapper().readTree(body);
		JsonNode nameNode = actualObj.path("host-default-list").path("list-items");
		List<String> hosts = nameNode.findValuesAsText("nameref");
		String[] s = new String[hosts.size()];
		hosts.toArray(s);
		return s;

	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #2
Source File: WBFailover.java    From java-client-api with Apache License 2.0 7 votes vote down vote up
private boolean isRunning(String host) {
	try {

		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(new AuthScope(host, 7997),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpGet get = new HttpGet("http://" + host + ":7997?format=json");
		HttpResponse response = client.execute(get);
		ResponseHandler<String> handler = new BasicResponseHandler();
		String body = handler.handleResponse(response);
		if (body.contains("Healthy")) {
			return true;
		}

	} catch (Exception e) {
		return false;
	}
	return false;
}
 
Example #3
Source File: NightscoutUploader.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private void postDeviceStatus(String baseURL, Header apiSecretHeader, DefaultHttpClient httpclient) throws Exception {
    String devicestatusURL = baseURL + "devicestatus";
    Log.i(TAG, "devicestatusURL: " + devicestatusURL);

    JSONObject json = new JSONObject();
    json.put("uploaderBattery", getBatteryLevel());
    String jsonString = json.toString();

    HttpPost post = new HttpPost(devicestatusURL);

    if (apiSecretHeader != null) {
        post.setHeader(apiSecretHeader);
    }

    StringEntity se = new StringEntity(jsonString);
    post.setEntity(se);
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");

    ResponseHandler responseHandler = new BasicResponseHandler();
    httpclient.execute(post, responseHandler);
}
 
Example #4
Source File: HttpUtils.java    From QVisual with Apache License 2.0 6 votes vote down vote up
public static String post(String url, String fileName, BufferedImage image) {
    Try<String> uploadedFile = Try.of(() -> {
        HttpClient client = HttpClientBuilder.create().build();

        HttpEntity entity = MultipartEntityBuilder
                .create()
                .setCharset(UTF_8)
                .setMode(BROWSER_COMPATIBLE)
                .addBinaryBody("file", getImageBytes(image), DEFAULT_BINARY, fileName)
                .build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);

        HttpResponse response = client.execute(httpPost);
        return new BasicResponseHandler().handleResponse(response);
    }).onFailure(t -> logger.error("[POST image]", t));

    return (uploadedFile.isSuccess()) ? uploadedFile.get() : null;
}
 
Example #5
Source File: HttpUtils.java    From QVisual with Apache License 2.0 6 votes vote down vote up
public static String post(String url, String fileName, String json) {
    Try<String> uploadedFile = Try.of(() -> {
        HttpClient client = HttpClientBuilder.create().build();

        HttpEntity entity = MultipartEntityBuilder
                .create()
                .setCharset(UTF_8)
                .setMode(BROWSER_COMPATIBLE)
                .addBinaryBody("file", json.getBytes(UTF_8), ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), UTF_8), fileName)
                .build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);

        HttpResponse response = client.execute(httpPost);
        return new BasicResponseHandler().handleResponse(response);
    }).onFailure(t -> logger.error("[POST json]", t));

    return (uploadedFile.isSuccess()) ? uploadedFile.get() : null;
}
 
Example #6
Source File: CSDNLoginApater.java    From crawler-jsoup-maven with Apache License 2.0 6 votes vote down vote up
public static String getText(String redirectLocation) {
    HttpGet httpget = new HttpGet(redirectLocation);
    // Create a response handler
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = "";
    try {
        responseBody = httpclient.execute(httpget, responseHandler);
    } catch (Exception e) {
        e.printStackTrace();
        responseBody = null;
    } finally {
        httpget.abort();
        // httpclient.getConnectionManager().shutdown();
    }
    return responseBody;
}
 
Example #7
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
public void testHttpProxy() throws IOException {
    Settings.setLoggingLevel("org.apache.http.wire", Level.DEBUG);
    Settings.setLoggingLevel("org.apache.http", Level.DEBUG);

    String proxyHost = Settings.getProperty("davmail.proxyHost");
    int proxyPort = Settings.getIntProperty("davmail.proxyPort");
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setProxy(proxy).setUserAgent(DavGatewayHttpClientFacade.IE_USER_AGENT);

    clientBuilder.setDefaultCredentialsProvider(getProxyCredentialProvider());

    try (CloseableHttpClient httpClient = clientBuilder.build()) {
        HttpGet httpget = new HttpGet("http://davmail.sourceforge.net/version.txt");
        try (CloseableHttpResponse response = httpClient.execute(httpget)) {
            String responseString = new BasicResponseHandler().handleResponse(response);
            System.out.println(responseString);
        }
    }
}
 
Example #8
Source File: QBFailover.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
private boolean isRunning(String host) {
	try {

		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(new AuthScope(host, 7997),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpGet get = new HttpGet("http://" + host + ":7997?format=json");
		HttpResponse response = client.execute(get);
		ResponseHandler<String> handler = new BasicResponseHandler();
		String body = handler.handleResponse(response);
		if (body.toLowerCase().contains("healthy")) {
			return true;
		} else {
			return false;
		}

	} catch (Exception e) {
		return false;
	}
}
 
Example #9
Source File: UploadHelper.java    From MedtronicUploader with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private void postDeviceStatus(String baseURL, DefaultHttpClient httpclient) throws Exception {
    String devicestatusURL = baseURL + "devicestatus";
    Log.i(TAG, "devicestatusURL: " + devicestatusURL);

    JSONObject json = new JSONObject();
    json.put("uploaderBattery", DexcomG4Activity.batLevel);
    String jsonString = json.toString();

    HttpPost post = new HttpPost(devicestatusURL);
    StringEntity se = new StringEntity(jsonString);
    post.setEntity(se);
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");

    ResponseHandler responseHandler = new BasicResponseHandler();
    httpclient.execute(post, responseHandler);
}
 
Example #10
Source File: JSONResponseHandler.java    From coursera-android with MIT License 6 votes vote down vote up
@Override
public List<EarthQuakeRec> handleResponse(HttpResponse response)
		throws ClientProtocolException, IOException {
	List<EarthQuakeRec> result = new ArrayList<EarthQuakeRec>();
	String JSONResponse = new BasicResponseHandler()
			.handleResponse(response);
	try {
		JSONObject object = (JSONObject) new JSONTokener(JSONResponse)
				.nextValue();
		JSONArray earthquakes = object.getJSONArray("earthquakes");
		for (int i = 0; i < earthquakes.length(); i++) {
			JSONObject tmp = (JSONObject) earthquakes.get(i);
			result.add(new EarthQuakeRec(
					tmp.getDouble("lat"),
					tmp.getDouble("lng"),
					tmp.getDouble("magnitude")));
		}
	} catch (JSONException e) {
		e.printStackTrace();
	}
	return result;
}
 
Example #11
Source File: BackupUtils.java    From opsgenie-configuration-backup with Apache License 2.0 6 votes vote down vote up
public static RateLimitsDto generateRateLimits(String apiKey, String opsGenieHost) throws IOException {
    try {
        HttpClient client = HttpClientBuilder.create().build();

        HttpGet httpGet = new HttpGet(opsGenieHost + "/v2/request-limits/");
        httpGet.addHeader(HttpHeaders.AUTHORIZATION, "GenieKey " + apiKey);

        String body = client.execute(httpGet, new BasicResponseHandler());
        DataDto result = new DataDto();
        BackupUtils.fromJson(result, body);

        return result.getData();
    } catch (Exception e) {
        logger.error("Could not initiate rate limits. " + e.getMessage());
        System.exit(1);
        return null;
    }
}
 
Example #12
Source File: AbstractHACCommunicationManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Send HTTP GET request to {@link #endpointUrl}, updates {@link #csrfToken}
 * token
 *
 * @return true if {@link #endpointUrl} is accessible
 * @throws IOException
 * @throws ClientProtocolException
 * @throws AuthenticationException
 */
protected void fetchCsrfTokenFromHac() throws ClientProtocolException, IOException, AuthenticationException {
	final HttpGet getRequest = new HttpGet(getEndpointUrl());

	try {
		final HttpResponse response = httpClient.execute(getRequest, getContext());
		final String responseString = new BasicResponseHandler().handleResponse(response);
		csrfToken = getCsrfToken(responseString);

		if (StringUtil.isBlank(csrfToken)) {
			throw new AuthenticationException(ErrorMessage.CSRF_TOKEN_CANNOT_BE_OBTAINED);
		}
	} catch (UnknownHostException error) {
		final String errorMessage = error.getMessage();
		final Matcher matcher = HACPreferenceConstants.HOST_REGEXP_PATTERN.matcher(getEndpointUrl());

		if (matcher.find() && matcher.group(1).equals(errorMessage)) {
			throw new UnknownHostException(
					String.format(ErrorMessage.UNKNOWN_HOST_EXCEPTION_MESSAGE_FORMAT, matcher.group(1)));
		}
		throw error;
	}
}
 
Example #13
Source File: HttpRequestUtil.java    From spark-jobs-rest-client with Apache License 2.0 6 votes vote down vote up
static <T extends SparkResponse>  T executeHttpMethodAndGetResponse(HttpClient client, HttpRequestBase httpRequest, Class<T> responseClass) throws FailedSparkRequestException {
    T response;
    try {
        final String stringResponse = client.execute(httpRequest, new BasicResponseHandler());
        if (stringResponse != null) {
            response = MapperWrapper.MAPPER.readValue(stringResponse, responseClass);
        } else {
            throw new FailedSparkRequestException("Received empty string response");
        }
    } catch (IOException e) {
        throw new FailedSparkRequestException(e);
    } finally {
        httpRequest.releaseConnection();
    }

    if (response == null) {
        throw new FailedSparkRequestException("An issue occured with the cluster's response.");
    }

    return response;
}
 
Example #14
Source File: htmlActivity.java    From styT with Apache License 2.0 6 votes vote down vote up
protected void httpClientWebData() {
    DefaultHttpClient httpClinet = new DefaultHttpClient();
    String pediyUrl = ped.getText().toString();

    HttpGet httpGet = new HttpGet(pediyUrl);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        String content = httpClinet.execute(httpGet, responseHandler);
        mHandler.obtainMessage(MSG_SUCCESS, content).sendToTarget();
    } catch (IOException e) {

        e.printStackTrace();
    }


}
 
Example #15
Source File: HunterRequest.java    From Burp-Hunter with GNU General Public License v3.0 6 votes vote down vote up
public String notifyHunter(byte[] content) throws IOException {
    try {
        String request = new String(content);
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
        HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
        String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
        StringEntity entity = new StringEntity(json);
        entity.setContentType("applicaiton/json");
        httpPost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPost);
        String responseString = new BasicResponseHandler().handleResponse(response);
        return responseString;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        
        Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "Error Notifying Probe Server!";
}
 
Example #16
Source File: SspClientTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void createNetworkTest() throws Exception {
    String networkName = "example network 1";
    String tenant_net_uuid = UUID.randomUUID().toString();
    SspClient sspClient = spy(new SspClient(apiUrl, username, password));

    HttpClient client = mock(HttpClient.class);
    doReturn(client).when(sspClient).getHttpClient();
    String body = "{\"uuid\":\"" + tenant_net_uuid + "\",\"name\":\"" + networkName
            + "\",\"tenant_uuid\":\"" + uuid + "\"}";
    when(client.execute(any(HttpUriRequest.class), any(BasicResponseHandler.class))).thenReturn(body);

    SspClient.TenantNetwork tnet = sspClient.createTenantNetwork(uuid, networkName);
    assertEquals(tnet.name, networkName);
    assertEquals(tnet.uuid, tenant_net_uuid);
    assertEquals(tnet.tenantUuid, uuid);
}
 
Example #17
Source File: NodeMetricsClient.java    From vespa with Apache License 2.0 6 votes vote down vote up
private Snapshot retrieveMetrics(ConsumerId consumer) {
    String metricsUri = node.metricsUri(consumer).toString();
    log.log(FINE, () -> "Retrieving metrics from host " + metricsUri);

    try {
        String metricsJson = httpClient.execute(new HttpGet(metricsUri), new BasicResponseHandler());
        var metricsBuilders = GenericJsonUtil.toMetricsPackets(metricsJson);
        var metrics = processAndBuild(metricsBuilders,
                                      new ServiceIdDimensionProcessor(),
                                      new ClusterIdDimensionProcessor(),
                                      new PublicDimensionsProcessor(MAX_DIMENSIONS));
        snapshotsRetrieved ++;
        log.log(FINE, () -> "Successfully retrieved " + metrics.size() + " metrics packets from " + metricsUri);

        return new Snapshot(Instant.now(clock), metrics);
    } catch (IOException e) {
        log.warning("Unable to retrieve metrics from " + metricsUri + ": " + Exceptions.toMessageString(e));
        return new Snapshot(Instant.now(clock), emptyList());
    }
}
 
Example #18
Source File: Item.java    From customer-review-crawler with The Unlicense 6 votes vote down vote up
/**
 * @return the RAW XML document of ItemLookup (Large Response) from Amazon
 *         product advertisement API
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws ClientProtocolException
 * @throws IOException
 */
public String getXMLLargeResponse() throws InvalidKeyException,
		NoSuchAlgorithmException, ClientProtocolException, IOException {
	String responseBody = "";
	String signedurl = signInput();
	try {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(signedurl);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		responseBody = httpclient.execute(httpget, responseHandler);
		// responseBody now contains the contents of the page
		// System.out.println(responseBody);
		httpclient.getConnectionManager().shutdown();
	} catch (Exception e) {
		System.out.println("Exception" + " " + itemID + " " + e.getClass());
	}
	return responseBody;
}
 
Example #19
Source File: WebClientTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void shouldAttachTraceIdWhenCallingAnotherServiceForHttpClient()
		throws Exception {
	Span span = this.tracer.nextSpan().name("foo").start();

	try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span)) {
		String response = this.httpClientBuilder.build().execute(
				new HttpGet("http://localhost:" + this.port),
				new BasicResponseHandler());

		then(response).isNotEmpty();
	}

	then(this.tracer.currentSpan()).isNull();
	then(this.spans).isNotEmpty().extracting("traceId", String.class)
			.containsOnly(span.context().traceIdString());
	then(this.spans).extracting("kind.name").contains("CLIENT");
}
 
Example #20
Source File: NodeMetricsFetcher.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public String get(String url) {
    try {
        return httpClient.execute(new HttpGet(url), new BasicResponseHandler());
    }
    catch (IOException e) {
        throw new UncheckedIOException("Could not get " + url, e);
    }
}
 
Example #21
Source File: AbstractHttpCheck.java    From appstatus with Apache License 2.0 5 votes vote down vote up
protected String doHttpGet(String url) throws ClientProtocolException,
		IOException {

	HttpClient httpclient = new DefaultHttpClient();
	HttpGet httpget = new HttpGet(url);
	ResponseHandler<String> responseHandler = new BasicResponseHandler();

	try {
		String responseBody = httpclient.execute(httpget, responseHandler);
		return responseBody;
	} finally {
		httpclient.getConnectionManager().shutdown();
	}

}
 
Example #22
Source File: SspClientTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void loginTest() throws Exception {
    SspClient sspClient = spy(new SspClient(apiUrl, username, password));

    HttpClient client = mock(HttpClient.class);
    doReturn(client).when(sspClient).getHttpClient();
    when(client.execute(any(HttpUriRequest.class), any(BasicResponseHandler.class))).thenReturn("");

    assertTrue(sspClient.login());
    assertTrue(sspClient.login());
    assertTrue(sspClient.login());
}
 
Example #23
Source File: AbstractHttpCheck.java    From appstatus with Apache License 2.0 5 votes vote down vote up
protected String doHttpGet(String url) throws ClientProtocolException,
		IOException {

	HttpClient httpclient = new DefaultHttpClient();
	HttpGet httpget = new HttpGet(url);
	ResponseHandler<String> responseHandler = new BasicResponseHandler();

	try {
		String responseBody = httpclient.execute(httpget, responseHandler);
		return responseBody;
	} finally {
		httpclient.getConnectionManager().shutdown();
	}

}
 
Example #24
Source File: AudioScrobblerService.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private String[] executeRequest(HttpUriRequest request) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 15000);

    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(request, responseHandler);
        return response.split("\\n");

    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #25
Source File: PrometheusV1Handler.java    From vespa with Apache License 2.0 5 votes vote down vote up
private HttpResponse valuesResponse(String consumer) {
    try {
        String uri = metricsProxyUri + consumerQuery(consumer);
        String prometheusText = httpClient.execute(new HttpGet(uri), new BasicResponseHandler());
        return new StringResponse(prometheusText);
    } catch (IOException e) {
        log.warning("Unable to retrieve metrics from " + metricsProxyUri + ": " + Exceptions.toMessageString(e));
        return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
 
Example #26
Source File: MetricsV2Handler.java    From vespa with Apache License 2.0 5 votes vote down vote up
private JsonResponse valuesResponse(String consumer) {
    try {
        String uri = metricsProxyUri + consumerQuery(consumer);
        String metricsJson = httpClient.execute(new HttpGet(uri), new BasicResponseHandler());
        return new JsonResponse(OK, metricsJson);
    } catch (IOException e) {
        log.warning("Unable to retrieve metrics from " + metricsProxyUri + ": " + Exceptions.toMessageString(e));
        return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
 
Example #27
Source File: NetworkService.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private void testUrlRedirection() {

            String urlToTest;
            String url = URL_REDIRECTION_TEST_URL;
            if (settingsService.getUrlRedirectType() == UrlRedirectType.NORMAL) {
                url += "?redirectFrom=" + settingsService.getUrlRedirectFrom();
                urlToTest = settingsService.getUrlRedirectFrom() + ".subsonic.org";
            } else {
                url += "?customUrl=" + settingsService.getUrlRedirectCustomUrl();
                urlToTest = settingsService.getUrlRedirectCustomUrl();
            }

            HttpGet request = new HttpGet(url);
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
            HttpConnectionParams.setSoTimeout(client.getParams(), 30000);

            try {
                urlRedirectionStatus.setText("Testing web address " + urlToTest + ". Please wait...");
                String response = client.execute(request, new BasicResponseHandler());
                urlRedirectionStatus.setText(response);

            } catch (Throwable x) {
                LOG.warn("Failed to test web address.", x);
                urlRedirectionStatus.setText("Failed to test web address. " + x.getMessage() + " (" + x.getClass().getSimpleName() + ")");
            } finally {
                client.getConnectionManager().shutdown();
            }
        }
 
Example #28
Source File: SonosServiceRegistration.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private String executeRequest(HttpUriRequest request) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 10000);

    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        return client.execute(request, responseHandler);

    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #29
Source File: SettingsService.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private void validateLicense() {
    String email = getLicenseEmail();
    Date date = getLicenseDate();

    if (email == null || date == null) {
        licenseValidated = false;
        return;
    }

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 120000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 120000);
    HttpGet method = new HttpGet("http://subsonic.org/backend/validateLicense.view" + "?email=" + StringUtil.urlEncode(email) +
            "&date=" + date.getTime() + "&version=" + versionService.getLocalVersion());
    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String content = client.execute(method, responseHandler);
        licenseValidated = content != null && !content.contains("false");
        if (!licenseValidated) {
            LOG.warn("License key is not valid.");
        }
        String[] lines = StringUtils.split(content);
        if (lines.length > 1) {
            licenseExpires = new Date(Long.parseLong(lines[1]));
        }

    } catch (Throwable x) {
        LOG.warn("Failed to validate license.", x);
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #30
Source File: LastFMScrobbler.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
private String[] executeRequest(HttpUriRequest request) throws ClientProtocolException, IOException {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(request, responseHandler);
        return response.split("\\r?\\n");
    }
}