List of usage examples for org.apache.http.client.methods RequestBuilder get
public static RequestBuilder get()
From source file:com.vmware.gemfire.tools.pulse.tests.junit.BaseServiceTest.java
/** * Logout to pulse server and close httpClient * To be called from setupAfterClass in each test class *///from w w w .j a v a 2 s . co m protected static void doLogout() throws Exception { System.out.println("BaseServiceTest :: Executing doLogout with user : admin, password : admin."); if (httpclient != null) { CloseableHttpResponse logoutResponse = null; try { HttpUriRequest logout = RequestBuilder.get().setUri(new URI(LOGOUT_URL)).build(); logoutResponse = httpclient.execute(logout); try { HttpEntity entity = logoutResponse.getEntity(); EntityUtils.consume(entity); } finally { if (logoutResponse != null) logoutResponse.close(); httpclient.close(); httpclient = null; } } catch (Exception failed) { logException(failed); throw failed; } System.out.println("BaseServiceTest :: Executed doLogout"); } else { System.out.println("BaseServiceTest :: User NOT logged-in"); } }
From source file:org.dasein.cloud.azure.platform.AzureSQLDatabaseSupportRequests.java
public RequestBuilder subscriptionMetaRequest() { RequestBuilder requestBuilder = RequestBuilder.get(); addAzureCommonHeaders(requestBuilder); requestBuilder//w w w . j a v a2s .co m .setUri(String.format(RESOURCE_SUBSCRIPTION_META, this.provider.getContext().getAccountNumber())); return requestBuilder; }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse get(String url, Header[] headers, final String defaultResponseCharset) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {/*from w ww . jav a 2 s . c o m*/ RequestBuilder _reqBuilder = RequestBuilder.get().setUri(url); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:cf.spring.servicebroker.CatalogTest.java
@Test public void spelCatalogCredentials() throws Exception { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(CONFIGURABLE_USERNAME, CONFIGURABLE_PASSWORD)); final SpringApplication application = new SpringApplication(SpelServiceBrokerCatalog.class); try (ConfigurableApplicationContext context = application.run(); CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider) .build();) {/*from w ww . j ava 2s . c o m*/ final HttpUriRequest catalogRequest = RequestBuilder.get() .setUri("http://localhost:8080" + Constants.CATALOG_URI).build(); final CloseableHttpResponse response = client.execute(catalogRequest); assertEquals(response.getStatusLine().getStatusCode(), 200); } }
From source file:org.dasein.cloud.azure.platform.AzureSQLDatabaseSupportRequests.java
public RequestBuilder getDatabase(String serverName, String databaseName) throws InternalException { RequestBuilder requestBuilder = RequestBuilder.get(); addAzureCommonHeaders(requestBuilder); requestBuilder.setUri(getEncodedUri(String.format(RESOURCE_DATABASE, this.provider.getContext().getAccountNumber(), serverName, databaseName))); return requestBuilder; }
From source file:edu.mit.scratch.ScratchSession.java
public ScratchCloudSession getCloudSession(final int projectID) throws ScratchProjectException { final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.getSessionID()); final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.getCSRFToken()); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); sessid.setDomain(".scratch.mit.edu"); sessid.setPath("/"); token.setDomain(".scratch.mit.edu"); token.setPath("/"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(lang);//from w w w . jav a 2 s .c o m cookieStore.addCookie(sessid); cookieStore.addCookie(token); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp = null; final HttpUriRequest project = RequestBuilder.get() .setUri("https://scratch.mit.edu/projects/" + projectID + "/").addHeader("Accept", "text/html") .addHeader("Referer", "https://scratch.mit.edu").build(); try { resp = httpClient.execute(project); } catch (final IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } String projectStr = null; try { projectStr = Scratch.consume(resp); } catch (IllegalStateException | IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } final Pattern p = Pattern.compile("cloudToken: '([a-zA-Z0-9\\-]+)'"); final Matcher m = p.matcher(projectStr); m.find(); final String cloudToken = m.group(1); return new ScratchCloudSession(this, cloudToken, projectID); }
From source file:jp.classmethod.aws.brian.BrianClient.java
@Override public List<String> listTriggerGroups() throws BrianClientException, BrianServerException { logger.debug("list trigger groups: {}"); HttpResponse httpResponse = null;// w w w . j av a 2 s .c o m try { URI uri = new URI(scheme, null, hostname, port, "/triggers", null, null); HttpUriRequest httpRequest = RequestBuilder.get().setUri(uri).build(); httpResponse = httpClientExecute(httpRequest); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("statusCode: {}", statusCode); if (statusCode == HttpStatus.SC_OK) { JsonNode tree = mapper.readTree(httpResponse.getEntity().getContent()); return StreamSupport.stream(tree.spliterator(), false).map(item -> item.textValue()) .collect(Collectors.toList()); } else if (statusCode >= 500) { throw new BrianServerException("status = " + statusCode); } else if (statusCode >= 400) { throw new BrianClientException("status = " + statusCode); } else { throw new Error("status = " + statusCode); } } catch (URISyntaxException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new BrianServerException(e); } catch (IllegalStateException e) { throw new Error(e); } finally { if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } }
From source file:edu.usu.sdl.apiclient.AbstractService.java
protected APIResponse callAPI(String apiPath, Map<String, String> parameters) { APIResponse response = null;// w w w . j a v a 2 s .c o m try { RequestConfig defaultRequestConfig = RequestConfig.custom().setCircularRedirectsAllowed(true).build(); RequestBuilder builder = RequestBuilder.get().setUri(new URI(loginModel.getServerUrl() + apiPath)) .addHeader(CONTENT_TYPE, MEDIA_TYPE_JSON).setConfig(defaultRequestConfig); if (parameters != null) { for (String key : parameters.keySet()) { builder.addParameter(key, parameters.get(key)); } } HttpUriRequest request = builder.build(); try (CloseableHttpResponse httpResponse = getClient().execute(request)) { response = new APIResponse(); response.setResponseCode(httpResponse.getStatusLine().getStatusCode()); HttpEntity entity1 = httpResponse.getEntity(); StringBuilder data = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader(entity1.getContent()))) { in.lines().forEach(line -> { data.append(line).append("\n"); }); } response.setResponseBody(data.toString()); EntityUtils.consume(entity1); } } catch (IOException | URISyntaxException ex) { throw new ConnectionException("Unable to Connect.", ex); } return response; }
From source file:org.dasein.cloud.azure.platform.AzureSQLDatabaseSupportRequests.java
public RequestBuilder getRecoverableDatabases(String serverName) { RequestBuilder requestBuilder = RequestBuilder.get(); addAzureCommonHeaders(requestBuilder); requestBuilder.setUri(String.format(RESOURCE_LIST_RECOVERABLE_DATABASES, this.provider.getContext().getAccountNumber(), serverName)); return requestBuilder; }
From source file:nl.opengeogroep.filesetsync.client.FilesetSyncer.java
private void retrieveFilesetList() throws IOException { final boolean cachedFileList = state.getFileListDate() != null && state.getFileListRemotePath().equals(fs.getRemote()) && (!fs.isHash() || state.isFileListHashed()) && SyncJobState.haveCachedFileList(fs.getName()); String s = "Retrieving file list"; if (cachedFileList) { s += String.format(" (last file list cached at %s)", FormatUtil.dateToString(state.getFileListDate())); }//w ww . jav a2 s. c o m action(s); try (CloseableHttpClient httpClient = HttpClientUtil.get()) { HttpUriRequest get = RequestBuilder.get().setUri(serverUrl + "list/" + fs.getRemote()) .addParameter("hash", fs.isHash() + "").addParameter("regexp", fs.getRegexp()).build(); if (cachedFileList) { get.addHeader(HttpHeaders.IF_MODIFIED_SINCE, HttpUtil.formatDate(state.getFileListDate())); } addExtraHeaders(get); // Request poorly encoded text format get.addHeader(HttpHeaders.ACCEPT, "text/plain"); ResponseHandler<List<FileRecord>> rh = new ResponseHandler<List<FileRecord>>() { @Override public List handleResponse(HttpResponse hr) throws ClientProtocolException, IOException { log.info("< " + hr.getStatusLine()); int status = hr.getStatusLine().getStatusCode(); if (status == SC_NOT_MODIFIED) { return null; } else if (status >= SC_OK && status < 300) { HttpEntity entity = hr.getEntity(); if (entity == null) { throw new ClientProtocolException("No response entity, invalid server URL?"); } try (InputStream in = entity.getContent()) { return Protocol.decodeFilelist(in); } } else { if (log.isTraceEnabled()) { String entity = hr.getEntity() == null ? null : EntityUtils.toString(hr.getEntity()); log.trace("Response body: " + entity); } else { EntityUtils.consumeQuietly(hr.getEntity()); } throw new ClientProtocolException("Server error: " + hr.getStatusLine()); } } }; log.info("> " + get.getRequestLine()); fileList = httpClient.execute(get, rh); if (fileList == null) { log.info("Cached file list is up-to-date"); fileList = SyncJobState.readCachedFileList(fs.getName()); } else { log.info("Filelist returned " + fileList.size() + " files"); /* Calculate last modified client-side, requires less server * memory */ long lastModified = -1; for (FileRecord fr : fileList) { lastModified = Math.max(lastModified, fr.getLastModified()); } if (lastModified != -1) { state.setFileListRemotePath(fs.getRemote()); state.setFileListDate(new Date(lastModified)); state.setFileListHashed(fs.isHash()); SyncJobState.writeCachedFileList(fs.getName(), fileList); SyncJobStatePersistence.persist(); } } } }