List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:com.vmware.gemfire.tools.pulse.tests.junit.BaseServiceTest.java
/** * Login to pulse server and setup httpClient for tests * To be called from setupBeforeClass in each test class *///from w w w. j a v a 2s.c o m protected static void doLogin() throws Exception { System.out.println("BaseServiceTest :: Executing doLogin with user : admin, password : admin."); CloseableHttpResponse loginResponse = null; try { BasicCookieStore cookieStore = new BasicCookieStore(); httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); HttpUriRequest login = RequestBuilder.post().setUri(new URI(LOGIN_URL)) .addParameter("j_username", "admin").addParameter("j_password", "admin").build(); loginResponse = httpclient.execute(login); try { HttpEntity entity = loginResponse.getEntity(); EntityUtils.consume(entity); System.out.println("BaseServiceTest :: HTTP request status : " + loginResponse.getStatusLine()); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { } else { for (int i = 0; i < cookies.size(); i++) { } } } finally { if (loginResponse != null) loginResponse.close(); } } catch (Exception failed) { logException(failed); throw failed; } System.out.println("BaseServiceTest :: Executed doLogin"); }
From source file:org.wuspba.ctams.ws.ITSoloResultController.java
private static void add() throws Exception { ITSoloContestController.add();//from www . java2 s . co m CTAMSDocument doc = new CTAMSDocument(); doc.getPeople().add(TestFixture.INSTANCE.elaine); doc.getVenues().add(TestFixture.INSTANCE.venue); doc.getJudges().add(TestFixture.INSTANCE.judgeAndy); doc.getJudges().add(TestFixture.INSTANCE.judgeJamie); doc.getJudges().add(TestFixture.INSTANCE.judgeBob); doc.getResults().add(TestFixture.INSTANCE.result5); doc.getSoloContests().add(TestFixture.INSTANCE.soloContest); doc.getSoloContestResults().add(TestFixture.INSTANCE.soloResult); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.soloResult.setId(doc.getSoloContestResults().get(0).getId()); for (Result r : doc.getSoloContestResults().get(0).getResults()) { if (r.getPoints() == TestFixture.INSTANCE.result1.getPoints()) { TestFixture.INSTANCE.result1.setId(r.getId()); } else if (r.getPoints() == TestFixture.INSTANCE.result2.getPoints()) { TestFixture.INSTANCE.result2.setId(r.getId()); } else if (r.getPoints() == TestFixture.INSTANCE.result3.getPoints()) { TestFixture.INSTANCE.result3.setId(r.getId()); } else if (r.getPoints() == TestFixture.INSTANCE.result4.getPoints()) { TestFixture.INSTANCE.result4.setId(r.getId()); } else if (r.getPoints() == TestFixture.INSTANCE.result5.getPoints()) { TestFixture.INSTANCE.result5.setId(r.getId()); } } EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:de.xwic.appkit.core.remote.client.URemoteAccessClient.java
/** * @param param// w w w. j a v a 2 s.co m * @param config * @return */ public static byte[] postRequest(final IRequestHelper helper, final RemoteSystemConfiguration config) { CloseableHttpResponse response = null; try { CloseableHttpClient client = PoolingHttpConnectionManager.getInstance().getClientInstance(config); HttpPost post = new HttpPost(helper.getTargetUrl()); post.setEntity(helper.getHttpEntity()); response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new RemoteDataAccessException(response.getStatusLine().getReasonPhrase()); } return EntityUtils.toByteArray(response.getEntity()); } catch (RemoteDataAccessException re) { throw re; } catch (Exception e) { throw new RemoteDataAccessException(e); } finally { if (response != null) { try { response.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } }
From source file:org.helm.notation2.wsadapter.MonomerWSLoader.java
/** * Loads the monomer categories using the URL configured in * {@code MonomerStoreConfiguration}.//www.j ava2 s . c o m * * @return List containing monomer categories * * @throws IOException * @throws URISyntaxException */ public static List<CategorizedMonomer> loadMonomerCategorization() throws IOException, URISyntaxException { List<CategorizedMonomer> config = new LinkedList<CategorizedMonomer>(); CloseableHttpClient httpclient = HttpClients.createDefault(); // There is no need to provide user credentials // HttpClient will attempt to access current user security context // through Windows platform specific methods via JNI. CloseableHttpResponse response = null; try { response = WSAdapterUtils.getResource( MonomerStoreConfiguration.getInstance().getWebserviceEditorCategorizationFullURL()); LOG.debug(response.getStatusLine().toString()); JsonFactory jsonf = new JsonFactory(); InputStream instream = response.getEntity().getContent(); JsonParser jsonParser = jsonf.createJsonParser(instream); config = deserializeEditorCategorizationConfig(jsonParser); LOG.debug(config.size() + " categorization info entries loaded"); EntityUtils.consume(response.getEntity()); } finally { if (response != null) { response.close(); } if (httpclient != null) { httpclient.close(); } } return config; }
From source file:myexamples.MyExamples.java
public static void getExample() throws IOException { HttpGet httpGet = new HttpGet("http://localhost:9200/gb/tweet/9"); CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try {//from w w w.j a v a 2 s . co m System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed if (entity1 != null) { long len = entity1.getContentLength(); if (len != -1 && len < 2048) { System.out.println(EntityUtils.toString(entity1)); } else { System.out.println("entity length=" + len); } } EntityUtils.consume(entity1); } finally { response1.close(); } }
From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java
private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException { final InputStream inputStream; if (response.getEntity() == null) { inputStream = new ByteArrayInputStream(new byte[0]); } else {/*from ww w.ja v a2 s. c o m*/ final InputStream i = response.getEntity().getContent(); if (i.markSupported()) { inputStream = i; } else { inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE); } } return new FilterInputStream(inputStream) { @Override public void close() throws IOException { response.close(); super.close(); } }; }
From source file:myexamples.MyExamples.java
public static String getTweet() throws IOException { String result = ""; HttpGet httpGet = new HttpGet("http://localhost:9200/gb/tweet/9"); CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try {//from w w w . j ava 2 s. c om System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed if (entity1 != null) { long len = entity1.getContentLength(); if (len != -1 && len < 2048) { // System.out.println(EntityUtils.toString(entity1)); result = EntityUtils.toString(entity1); } else { System.out.println("entity length=" + len); } } EntityUtils.consume(entity1); } finally { response1.close(); } return result; }
From source file:com.lhings.java.http.WebServiceCom.java
private static HttpResponse executeRequest(HttpRequestBase request) throws IOException { CloseableHttpClient hc = HttpClients.createDefault(); CloseableHttpResponse response = hc.execute(request); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(response.getStatusLine().getStatusCode()); httpResponse.setStatusMessage(response.getStatusLine().getReasonPhrase()); // ResponseHandler<String> handler = new BasicResponseHandler(); // String responseBody = handler.handleResponse(response); httpResponse.setResponseBody(EntityUtils.toString(response.getEntity())); return httpResponse; }
From source file:client.QueryLastFm.java
License:asdf
public static void findSimilarTracks(PrintWriter track_id_out, String sourceMbid, String trackName, String artistName) throws Exception { String destMbid;/*from w w w.j av a 2s .c o m*/ CloseableHttpClient httpclient = HttpClients.createDefault(); try { Thread.sleep(50); //1000 milliseconds is one second. } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } try { URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/") .setParameter("method", "track.getsimilar").setParameter("artist", artistName) .setParameter("track", trackName).setParameter("limit", "10") .setParameter("api_key", "88858618961414f8bec919bddd057044").build(); // new URIBuilder(). HttpGet request = new HttpGet(uri); // request. // This is useful for last.fm logging and preventing them from blocking this client request.setHeader(HttpHeaders.USER_AGENT, "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use"); CloseableHttpResponse response = httpclient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); try { if (statusCode == 200) { HttpEntity entity1 = response.getEntity(); BufferedReader br = new BufferedReader( new InputStreamReader((response.getEntity().getContent()))); Document document = builder.parse((response.getEntity().getContent())); Element root = document.getDocumentElement(); root.normalize(); NodeList mbidList = root.getElementsByTagName("mbid"); // System.out.println("mbid" + mbidList.getLength()); for (int n = 0; n < mbidList.getLength(); n++) { Node attribute = mbidList.item(n); if (mbidList.item(n).hasChildNodes()) { if (mbidList.item(n).getParentNode().getNodeName().matches("track")) // to get correct mbid { destMbid = mbidList.item(n).getFirstChild().getNodeValue(); // track_id_out.print(sourceMbid); // track_id_out.print(","); // track_id_out.println(destMbid); if (isAlreadyInserted(sourceMbid, destMbid)) // if not inserted , insert into map { // System.out.println(sourceMbid + "---" + destMbid); // track_id_out.print(sourceMbid); // track_id_out.print(","); // track_id_out.println(destMbid); // continue; } /*if(isAlreadyInserted(sourceMbid, destMbid)) { System.out.println("Ok got the match !!"); }*/ else { track_id_out.print(sourceMbid); track_id_out.print(","); track_id_out.println(destMbid); // // track_id_out.print(","); // track_id_out.println("Undirected"); } // track_id_out.print() } } } } } finally { response.close(); } } finally { httpclient.close(); } }
From source file:eu.diacron.crawlservice.app.Util.java
public static void getAllCrawls() { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME, Configuration.REMOTE_CRAWLER_PASS)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {//from w w w .ja v a 2 s.c om //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl"); HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); System.out.println(response.getEntity().getContent()); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } }