List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:capabilities.Browser.java
@Override public String dbSearch(String userAgent) throws Exception { String urlInicio, urlCapacidades, urlFim, urlPath; String capacidades = "mobile_browser_version%0D%0A" + "mobile_browser"; // Montagem URL de acesso ao Introspector Servlet WURFL urlPath = "http://localhost:8080/AdapterAPI/"; // Caminho do projeto urlInicio = "introspector.do?action=Form&form=pippo&ua=" + userAgent; urlCapacidades = "&capabilities=" + capacidades; urlFim = "&wurflEngineTarget=performance&wurflUserAgentPriority=OverrideSideloadedBrowserUserAgent"; // Conexo com o Servlet DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(urlPath + urlInicio + urlCapacidades + urlFim); getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); }/*from w w w . j a v a2 s . co m*/ BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String buffer; String dados = ""; //System.out.println("Output from Server .... \n"); while ((buffer = br.readLine()) != null) { dados += buffer; } //System.out.println("Sada:\n\t" + dados); httpClient.getConnectionManager().shutdown(); JSONObject my_obj; JSONParser parser = new JSONParser(); my_obj = (JSONObject) parser.parse(dados); JSONObject capabilities = (JSONObject) my_obj.get("capabilities"); return capabilities.toJSONString(); }
From source file:org.wso2.identity.sample.webapp.APIInvoker.java
private String callRESTep(String ep) throws Exception { PlatformUtils.setKeyStoreProperties(); PlatformUtils.setKeyStoreParams();/*from www . j a v a 2 s . c om*/ DefaultHttpClient httpClient = new DefaultHttpClient(); try { SSLSocketFactory sf = null; SSLContext sslContext = null; StringWriter writer; try { sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); } catch (NoSuchAlgorithmException e) { //<YourErrorHandling> } catch (KeyManagementException e) { //<YourErrorHandling> } try { sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { //<YourErrorHandling> } Scheme scheme = new Scheme("https", 8243, sf); httpClient.getConnectionManager().getSchemeRegistry().register(scheme); HttpGet get = new HttpGet(ep); // add header get.setHeader("Content-Type", "text/xml;charset=UTF-8"); get.setHeader("Authorization", "Bearer " + oauthToken); get.setHeader("x-saml-assertion", SamlConsumerManager.getEncodedAssertion()); CloseableHttpResponse response = httpClient.execute(get); try { String result = EntityUtils.toString(response.getEntity()); System.out.println("API RESULT" + result); return result; } finally { response.close(); } } finally { httpClient.close(); } }
From source file:com.google.code.maven.plugin.http.client.HttpClientMojo.java
@SuppressWarnings("unchecked") public void execute() throws MojoExecutionException, MojoFailureException { getLog().debug("loading context..."); beanContext = new BeanContext(project); beanContext.registerConfigFactory(proxy); beanContext.registerConfigFactory(request); getLog().debug("registering bean defintions..."); request.setId("request"); String requestName = this.request.registerBeanDefinition(beanContext.getBeanFactory()); getLog().debug("request registered."); String proxyName = null;//from ww w . ja v a 2s . c o m if (proxy != null) { proxy.setId("proxy"); proxyName = this.proxy.registerBeanDefinition(beanContext.getBeanFactory()); getLog().debug("proxy registered."); } List<String> transformersIds = new ArrayList<String>(transformers.length); for (TransformerBeanDefinition transformerBeanDefinition : transformers) { transformersIds.add(transformerBeanDefinition.registerBeanDefinition(beanContext.getBeanFactory())); getLog().debug("transformer registered."); } getLog().debug("building beans..."); Request request = beanContext.getBean(requestName, Request.class); getLog().debug("request built."); Proxy proxy = null; if (proxyName != null) { proxy = beanContext.getBean(proxyName, Proxy.class); getLog().debug("proxy built."); } for (String transformerId : transformersIds) { beanContext.getBean(transformerId, Transformer.class); getLog().debug("transformer built."); } DefaultHttpClient httpclient = new DefaultHttpClient(); try { // client HttpResponse response = HttpRequestUtils.query(httpclient, request, proxy, getLog()); long transformTime = System.currentTimeMillis(); Object current = response; for (String transformerId : transformersIds) { Transformer transformer = beanContext.getBean(transformerId, Transformer.class); current = transformer.transform(current, getLog()); } getLog().info("Response processed in " + (System.currentTimeMillis() - transformTime) + "ms"); httpclient.getConnectionManager().shutdown(); } catch (ClassCastException cce) { if (failSafe) { getLog().warn("invalid transformation flow", cce); } else { throw new MojoExecutionException("invalid transformation flow", cce); } } catch (ClientProtocolException cpe) { if (failSafe) { getLog().warn("invalid protocol", cpe); } else { throw new MojoExecutionException("invalid protocol", cpe); } } catch (IOException ioe) { if (failSafe) { getLog().warn("network failure", ioe); } else { throw new MojoExecutionException("network failure", ioe); } } catch (MojoExecutionException mee) { if (failSafe) { getLog().warn("mojo execution failure", mee); } else { throw mee; } } }
From source file:capabilities.Display.java
@Override public String dbSearch(String userAgent) throws Exception { String urlInicio, urlCapacidades, urlFim, urlPath; String capacidades = "resolution_width%0D%0A" // Largura da tela em pixels + "resolution_height%0D%0A" // Altura da tela em pixels + "columns%0D%0A" // Numero de colunas apresentadas + "rows%0D%0A" // Numero de linhas apresentadas + "physical_screen_width%0D%0A" // Largura da tela em milimetros + "physical_screen_height%0D%0A" // Altura da tela em milimetros + "dual_orientation"; // Se pode ter duas orientacoes // Montagem URL de acesso ao Introspector Servlet WURFL urlPath = "http://localhost:8080/AdapterAPI/"; // Caminho do projeto urlInicio = "introspector.do?action=Form&form=pippo&ua=" + userAgent; urlCapacidades = "&capabilities=" + capacidades; urlFim = "&wurflEngineTarget=performance&wurflUserAgentPriority=OverrideSideloadedBrowserUserAgent"; // Conexo com o Servlet DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(urlPath + urlInicio + urlCapacidades + urlFim); getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); }/* w w w . ja v a2 s.c om*/ BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String buffer; String dados = ""; //System.out.println("Output from Server .... \n"); while ((buffer = br.readLine()) != null) { dados += buffer; } //System.out.println("Sada:\n\t" + dados); httpClient.getConnectionManager().shutdown(); JSONObject my_obj; JSONParser parser = new JSONParser(); my_obj = (JSONObject) parser.parse(dados); JSONObject capabilities = (JSONObject) my_obj.get("capabilities"); return capabilities.toJSONString(); }
From source file:com.onesite.commons.net.http.rest.client.RestClient.java
/** * Create a POST request to the given url posting the ContentBody to the content tag * URL = scheme://host:port/path?query_string * // w ww. j ava 2 s . co m * @param path * @param params * @param body * @return * @throws Exception */ public int post(String path, Map<String, String> params, ContentBody body) throws Exception { String url = this.generateEncodeURLString(path, params); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(url); request.addHeader("accept", "application/json"); MultipartEntity entity = new MultipartEntity(); entity.addPart("content", body); request.setEntity(entity); try { HttpResponse response = httpClient.execute(this.target, request); try { this.processHttpResponse(response); } catch (Exception e) { log.error("Error processing HttpResponse from " + url); throw e; } } catch (Exception e) { log.error("Error occurred during calling to " + url); throw e; } finally { httpClient.getConnectionManager().shutdown(); } return status; }
From source file:com.google.pubsub.clients.common.MetricsHandler.java
private void initialize() { synchronized (this) { try {// w w w . j ava2s. com HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); if (credential.createScopedRequired()) { credential = credential.createScoped( Collections.singletonList("https://www.googleapis.com/auth/cloud-platform")); } monitoring = new Monitoring.Builder(transport, jsonFactory, credential) .setApplicationName("Cloud Pub/Sub Loadtest Framework").build(); String zoneId; String instanceId; try { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.addRequestInterceptor(new RequestAcceptEncoding()); httpClient.addResponseInterceptor(new ResponseContentEncoding()); HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000); HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000); HttpConnectionParams.setSoKeepalive(httpClient.getParams(), true); HttpConnectionParams.setStaleCheckingEnabled(httpClient.getParams(), false); HttpConnectionParams.setTcpNoDelay(httpClient.getParams(), true); SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); httpClient.setKeepAliveStrategy((response, ctx) -> 30); HttpGet zoneIdRequest = new HttpGet( "http://metadata.google.internal/computeMetadata/v1/instance/zone"); zoneIdRequest.setHeader("Metadata-Flavor", "Google"); HttpResponse zoneIdResponse = httpClient.execute(zoneIdRequest); String tempZoneId = EntityUtils.toString(zoneIdResponse.getEntity()); if (tempZoneId.lastIndexOf("/") >= 0) { zoneId = tempZoneId.substring(tempZoneId.lastIndexOf("/") + 1); } else { zoneId = tempZoneId; } HttpGet instanceIdRequest = new HttpGet( "http://metadata.google.internal/computeMetadata/v1/instance/id"); instanceIdRequest.setHeader("Metadata-Flavor", "Google"); HttpResponse instanceIdResponse = httpClient.execute(instanceIdRequest); instanceId = EntityUtils.toString(instanceIdResponse.getEntity()); } catch (IOException e) { log.info("Unable to connect to metadata server, assuming not on GCE, setting " + "defaults for instance and zone."); instanceId = "local"; zoneId = "us-east1-b"; // Must use a valid cloud zone even if running local. } monitoredResource.setLabels( ImmutableMap.of("project_id", project, "instance_id", instanceId, "zone", zoneId)); createMetrics(); } catch (IOException e) { log.error("Unable to initialize MetricsHandler, trying again.", e); executor.execute(this::initialize); } catch (GeneralSecurityException e) { log.error("Unable to initialize MetricsHandler permanently, credentials error.", e); } } }
From source file:io.github.tavernaextras.biocatalogue.integration.config.BioCataloguePluginConfigurationPanel.java
/** * Saves recent changes to the configuration parameter map. * Some input validation is performed as well. *//* ww w . java2 s . c om*/ private void applyChanges() { // --- BioCatalogue BASE URL --- String candidateBaseURL = tfBioCatalogueAPIBaseURL.getText(); if (candidateBaseURL.length() == 0) { JOptionPane.showMessageDialog(this, "Service Catalogue base URL must not be blank", "Service Catalogue Configuration", JOptionPane.WARNING_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } else { try { new URL(candidateBaseURL); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Currently set Service Catalogue instance URL is not valid\n." + "Please check the URL and try again.", "Service Catalogue Configuration", JOptionPane.WARNING_MESSAGE); tfBioCatalogueAPIBaseURL.selectAll(); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } // check if the base URL has changed from the last saved state if (!candidateBaseURL.equals( configuration.getProperty(BioCataloguePluginConfiguration.SERVICE_CATALOGUE_BASE_URL))) { // Perform various checks on the new URL // Do a GET with "Accept" header set to "application/xml" // We are expecting a 200 OK and an XML doc in return that // contains the BioCataogue version number element. DefaultHttpClient httpClient = new DefaultHttpClient(); // Set the proxy settings, if any if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).equals("")) { // Instruct HttpClient to use the standard // JRE proxy selector to obtain proxy information ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Do we need to authenticate the user to the proxy? if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).equals("")) { // Add the proxy username and password to the list of credentials httpClient.getCredentialsProvider().setCredentials( new AuthScope(System.getProperty(PROXY_HOST), Integer.parseInt(System.getProperty(PROXY_PORT))), new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME), System.getProperty(PROXY_PASSWORD))); } } HttpGet httpGet = new HttpGet(candidateBaseURL); httpGet.setHeader("Accept", APPLICATION_XML_MIME_TYPE); // Execute the request HttpContext localContext = new BasicHttpContext(); HttpResponse httpResponse; try { httpResponse = httpClient.execute(httpGet, localContext); } catch (Exception ex1) { logger.error( "Service Catalogue preferences configuration: Failed to do " + httpGet.getRequestLine(), ex1); // Warn the user JOptionPane.showMessageDialog(this, "Failed to connect to the URL of the Service Catalogue instance.\n" + "Please check the URL and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); // Release resource httpClient.getConnectionManager().shutdown(); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { // HTTP/1.1 200 OK HttpEntity httpEntity = httpResponse.getEntity(); String contentType = httpEntity.getContentType().getValue().toLowerCase().trim(); logger.info( "Service Catalogue preferences configuration: Got 200 OK when testing the Service Catalogue instance by doing " + httpResponse.getStatusLine() + ". Content type of response " + contentType); if (contentType.startsWith(APPLICATION_XML_MIME_TYPE)) { String value = null; Document doc = null; try { value = readResponseBodyAsString(httpEntity).trim(); // Try to read this string into an XML document SAXBuilder builder = new SAXBuilder(); byte[] bytes = value.getBytes("UTF-8"); doc = builder.build(new ByteArrayInputStream(bytes)); } catch (Exception ex2) { logger.error( "Service Catalogue preferences configuration: Failed to build an XML document from the response.", ex2); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response body when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } finally { // Release resource httpClient.getConnectionManager().shutdown(); } // Get the version element from the XML document Attribute apiVersionAttribute = doc.getRootElement().getAttribute(API_VERSION); if (apiVersionAttribute != null) { String apiVersion = apiVersionAttribute.getValue(); String versions[] = apiVersion.split("[.]"); String majorVersion = versions[0]; String minorVersion = versions[1]; try { //String patchVersion = versions[2]; // we are not comparing the patch versions String supportedMajorVersion = MIN_SUPPORTED_BIOCATALOGUE_API_VERSION[0]; String supportedMinorVersion = MIN_SUPPORTED_BIOCATALOGUE_API_VERSION[1]; Integer iSupportedMajorVersion = Integer.parseInt(supportedMajorVersion); Integer iMajorVersion = Integer.parseInt(majorVersion); Integer iSupportedMinorVersion = Integer.parseInt(supportedMinorVersion); Integer iMinorVersion = Integer.parseInt(minorVersion); if (!(iSupportedMajorVersion == iMajorVersion && iSupportedMinorVersion <= iMinorVersion)) { // Warn the user JOptionPane.showMessageDialog(this, "The version of the Service Catalogue instance you are trying to connect to is not supported.\n" + "Please change the URL and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } } catch (Exception e) { logger.error(e); } } // if null - we'll try to do our best to connect to BioCatalogue anyway } else { logger.error( "Service Catalogue preferences configuration: Failed to get the expected response content type when testing the Service Catalogue instance. " + httpGet.getRequestLine() + " returned content type '" + contentType + "'; expected response content type is 'application/xml'."); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response content type when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Plugin", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } } else { logger.error( "Service Catalogue preferences configuration: Failed to get the expected response status code when testing the Service Catalogue instance. " + httpGet.getRequestLine() + " returned the status code " + httpResponse.getStatusLine().getStatusCode() + "; expected status code is 200 OK."); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response status code when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } // Warn the user of the changes in the BioCatalogue base URL JOptionPane.showMessageDialog(this, "You have updated the Service Catalogue base URL.\n" + "This does not take effect until you restart Taverna.", "Service catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); } // the new base URL seems to be valid - can save it into config // settings configuration.setProperty(BioCataloguePluginConfiguration.SERVICE_CATALOGUE_BASE_URL, candidateBaseURL); /* // also update the base URL in the BioCatalogueClient BioCatalogueClient.getInstance() .setBaseURL(candidateBaseURL);*/ } }
From source file:net.seedboxer.seedroid.utils.RestClient.java
private void executeRequest(HttpUriRequest request, String url) { DefaultHttpClient client = new DefaultHttpClient(); if (credProvider != null) { client.setCredentialsProvider(credProvider); }/*w ww . j a va2 s . c om*/ HttpResponse httpResponse; try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); response = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } }
From source file:juzu.impl.bridge.context.AbstractContextClientTestCase.java
protected void test(URL initialURL, String kind) throws Exception { driver.get(initialURL.toString());//w w w . j a v a 2 s . co m WebElement link = driver.findElement(By.id(kind)); contentLength = -1; charset = null; contentType = null; content = null; URL url = new URL(link.getAttribute("href")); DefaultHttpClient client = new DefaultHttpClient(); // Little trick to force redirect after post client.setRedirectStrategy(new DefaultRedirectStrategy() { @Override protected boolean isRedirectable(String method) { return true; } }); try { HttpPost post = new HttpPost(url.toURI()); post.setEntity(new StringEntity("foo", ContentType.create("application/octet-stream", "UTF-8"))); HttpResponse response = client.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(3, contentLength); assertEquals("UTF-8", charset); assertEquals("application/octet-stream; charset=UTF-8", contentType); assertEquals("foo", content); assertEquals(kind, AbstractContextClientTestCase.kind); } finally { client.getConnectionManager().shutdown(); } }
From source file:se.vgregion.incidentreport.pivotaltracker.impl.PivotalTrackerServiceImpl.java
private String getStoriesForProject(String projectId, String token) { if (token == null) { throw new RuntimeException("Token cannot be null. Please set it first."); }//from ww w . ja v a 2 s .c om DefaultHttpClient client = getNewClient(); String result = null; try { HttpResponse response = HTTPUtils.makeRequest(GET_PROJECT + "/" + projectId + "/stories", token, client); HttpEntity entity = response.getEntity(); // String xml = convertStreamToString(entity.getContent()); // System.out.println(xml); // Convert the xml response into an object // result = getProjectData((entity.getContent())); } catch (Exception e) { throw new RuntimeException("TODO: Handle this exception better", e); } finally { client.getConnectionManager().shutdown(); } return result; }