List of usage examples for org.apache.http.client ResponseHandler ResponseHandler
ResponseHandler
From source file:com.vsct.strowgr.monitoring.aggregator.nsq.NsqLookupClient.java
public Set<String> getTopics() throws UnavailableNsqException { try {// w w w . j a v a2 s. co m LOGGER.info("Listing all nsq topics"); HttpGet uri = new HttpGet("http://" + host + ":" + port + TOPICS_ENDPOINT); return client.execute(uri, new ResponseHandler<Set<String>>() { @Override public Set<String> handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { int status = httpResponse.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = httpResponse.getEntity(); NsqLookupResponse<NsqLookupTopics> nsqResponse = mapper.readValue(entity.getContent(), new TypeReference<NsqLookupResponse<NsqLookupTopics>>() { }); return nsqResponse.data.topics; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }); } catch (IOException e) { LOGGER.error("error while querying nsqlookup for list of topics"); throw new UnavailableNsqException(e); } }
From source file:com.ny.apps.executor.TencentWeiboOAuth2.java
public String getCode(String APPKEY, String APPSECRET) throws Exception { String code = null;//ww w . ja v a 2 s . c o m CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(prepareGetUrl()); System.out.println(prepareGetUrl().toASCIIString()); logger.info("executing request " + httpGet.getURI()); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); return entity == null ? null : EntityUtils.toString(entity); } else { throw new ClientProtocolException("Unexpected response status: " + statusCode); } } }; try { String responseBody = client.execute(httpGet, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); System.out.println("----------------------------------------"); } finally { client.close(); } return code; }
From source file:eu.seaclouds.platform.dashboard.http.HttpRequestBuilder.java
public HttpRequestBuilder() { this.scheme = DEFAULT_SCHEME; this.responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); }/* w w w . jav a 2 s . c om*/ } }; }
From source file:com.netflix.http4.NFHttpClientTest.java
@Test public void testNFHttpClient() throws Exception { NFHttpClient client = NFHttpClientFactory.getNFHttpClient("www.google.com", 80); ThreadSafeClientConnManager cm = (ThreadSafeClientConnManager) client.getConnectionManager(); cm.setDefaultMaxPerRoute(10);// w w w . j a v a 2s. c o m HttpGet get = new HttpGet("www.google.com"); ResponseHandler<Integer> respHandler = new ResponseHandler<Integer>() { public Integer handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); String contentStr = EntityUtils.toString(entity); return contentStr.length(); } }; long contentLen = client.execute(get, respHandler); assertTrue(contentLen > 0); }
From source file:es.uned.dia.jcsombria.softwarelinks.transport.HttpTransport.java
public Object send(String request) throws Exception { Object response = null;//from w w w . ja va 2 s.co m CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverURL.toString()); httppost.setEntity(new StringEntity(request)); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httppost, responseHandler); response = responseBody; } finally { httpclient.close(); } return response; }
From source file:eu.esdihumboldt.hale.io.codelist.InspireCodeListAdvisor.java
@Override public void copyResource(LocatableInputSupplier<? extends InputStream> resource, final Path target, IContentType resourceType, boolean includeRemote, IOReporter reporter) throws IOException { URI uri = resource.getLocation(); String uriScheme = uri.getScheme(); if (uriScheme.equals("http")) { // Get the response for the given uri Response response = INSPIRECodeListReader.getResponse(uri); // Handle the fluent response response.handleResponse(new ResponseHandler<Boolean>() { @Override/*from www . j ava 2s . c o m*/ public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (status.getStatusCode() >= 300) { throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException(); } // Copy the resource file to the target path Files.copy(entity.getContent(), target); return true; } }); } else { super.copyResource(resource, target, resourceType, includeRemote, reporter); } }
From source file:io.soabase.example.hello.HelloResourceApache.java
@GET public String getHello(@Context HttpHeaders headers) throws Exception { String result = "Service Name: " + info.getServiceName() + "\nInstance Name: " + info.getInstanceName() + "\nRequest Id: " + SoaRequestId.get(headers) + "\n"; URI uri = new URIBuilder().setHost(ClientUtils.serviceNameToHost("goodbye")).setPath("/goodbye").build(); HttpGet get = new HttpGet(uri); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override//from www. j a v a 2 s. co m public String handleResponse(HttpResponse response) throws IOException { return CharStreams.toString(new InputStreamReader(response.getEntity().getContent())); } }; String value = client.execute(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), get, responseHandler); return result + "\nGoodbye app says: \n\t" + value; }
From source file:tv.icntv.common.HttpClientUtil.java
/** * Get content by url as string// w w w.ja va2s .c o m * * @param url original url * @return page content * @throws java.io.IOException */ public static String getContent(String url) throws IOException { // construct request HttpGet request = new HttpGet(url); request.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")); request.setConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT).build()); // construct response handler ResponseHandler<String> handler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); // status if (status.getStatusCode() != HttpStatus.SC_OK) { throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()); } // get encoding in header String encoding = getPageEncoding(response); boolean encodingFounded = true; if (Strings.isNullOrEmpty(encoding)) { encodingFounded = false; encoding = "iso-8859-1"; } // get content and find real encoding HttpEntity entity = response.getEntity(); if (entity == null) { return null; } // get content byte[] contentBytes = EntityUtils.toByteArray(entity); if (contentBytes == null) { return null; } // found encoding if (encodingFounded) { return new String(contentBytes, encoding); } // attempt to discover encoding String rawContent = new String(contentBytes, DEFAULT_ENCODING); Matcher matcher = PATTERN_HTML_CHARSET.matcher(rawContent); if (matcher.find()) { String realEncoding = matcher.group(1); if (!encoding.equalsIgnoreCase(realEncoding)) { // bad luck :( return new String(rawContent.getBytes(encoding), realEncoding); } } // not found right encoding :) return rawContent; } }; // execute CloseableHttpClient client = HttpClientHolder.getClient(); return client.execute(request, handler); }
From source file:eu.eubrazilcc.lvl.core.TrustedHttpsClientTest.java
@Test public void test() { System.out.println("TrustedHttpsClientTest.test()"); try {/*from w ww . j a v a2 s.c o m*/ try (final TrustedHttpsClient httpClient = new TrustedHttpsClient()) { final ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { assertThat("HTTP response is not null", response, notNullValue()); assertThat("Status line is not null", response.getStatusLine(), notNullValue()); assertThat("Status coincides with expected", response.getStatusLine().getStatusCode(), allOf(greaterThanOrEqualTo(200), lessThan(300))); final HttpEntity entity = response.getEntity(); assertThat("Entity is not null", entity, notNullValue()); return entity != null ? EntityUtils.toString(entity) : null; } }; final String payload = httpClient.executeGet("https://www.google.es", null, responseHandler); assertThat("Content is not null", payload, notNullValue()); assertThat("Content not is empty", isNotBlank(payload)); /* uncomment for additional output System.out.println(" >> Server response: " + payload); */ } } catch (Exception e) { e.printStackTrace(System.err); fail("TrustedHttpsClientTest.test() failed: " + e.getMessage()); } finally { System.out.println("TrustedHttpsClientTest.test() has finished"); } }
From source file:nl.surfnet.coin.selenium.CorsHeaderTestSelenium.java
@Test public void preflight() throws Exception { HttpClient client = new DefaultHttpClient(); HttpUriRequest req = new HttpOptions(getApiBaseUrl() + OS_URL); req.setHeader("Origin", "localhost"); client.execute(req, new ResponseHandler<Object>() { @Override// ww w .ja v a2s .c o m public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertThat("response header Access-Control-Allow-Methods should contain 'GET'", response.getFirstHeader("Access-Control-Allow-Methods").getValue(), containsString("GET")); assertThat("No content should be served on a preflight request", response.getEntity().getContentLength(), equalTo(0L)); return null; } }); }