List of usage examples for org.apache.http.impl.client HttpClientBuilder create
public static HttpClientBuilder create()
From source file:interoperabilite.webservice.client.ClientWithRequestFuture.java
public static void main(String[] args) throws Exception { // the simplest way to create a HttpAsyncClientWithFuture HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build(); ExecutorService execService = Executors.newFixedThreadPool(5); FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient, execService);/*w ww.ja va2s. co m*/ try { // Because things are asynchronous, you must provide a ResponseHandler ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() { @Override public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { // simply return true if the status was OK return response.getStatusLine().getStatusCode() == 200; } }; // Simple request ... HttpGet request1 = new HttpGet("http://httpbin.org/get"); HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1, HttpClientContext.create(), handler); Boolean wasItOk1 = futureTask1.get(); System.out.println("It was ok? " + wasItOk1); // Cancel a request try { HttpGet request2 = new HttpGet("http://httpbin.org/get"); HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2, HttpClientContext.create(), handler); futureTask2.cancel(true); Boolean wasItOk2 = futureTask2.get(); System.out.println("It was cancelled so it should never print this: " + wasItOk2); } catch (CancellationException e) { System.out.println("We cancelled it, so this is expected"); } // Request with a timeout HttpGet request3 = new HttpGet("http://httpbin.org/get"); HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3, HttpClientContext.create(), handler); Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk3); FutureCallback<Boolean> callback = new FutureCallback<Boolean>() { @Override public void completed(Boolean result) { System.out.println("completed with " + result); } @Override public void failed(Exception ex) { System.out.println("failed with " + ex.getMessage()); } @Override public void cancelled() { System.out.println("cancelled"); } }; // Simple request with a callback HttpGet request4 = new HttpGet("http://httpbin.org/get"); // using a null HttpContext here since it is optional // the callback will be called when the task completes, fails, or is cancelled HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4, HttpClientContext.create(), handler, callback); Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk4); } finally { requestExecService.close(); } }
From source file:com.mycompany.mavenpost.HttpTest.java
public static void main(String args[]) throws UnsupportedEncodingException, IOException { System.out.println("this is a test program"); HttpPost httppost = new HttpPost("https://app.monsum.com/api/1.0/api.php"); // Request parameters and other properties. String auth = DEFAULT_USER + ":" + DEFAULT_PASS; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes()); String authHeader = "Basic " + new String(encodedAuth); //String authHeader = "Basic " +"YW5kcmVhcy5zZWZpY2hhQG1hcmtldHBsYWNlLWFuYWx5dGljcy5kZTo5MGRkYjg3NjExMWRiNjNmZDQ1YzUyMjdlNTNmZGIyYlhtMUJQQm03OHhDS1FUVm1OR1oxMHY5TVVyZkhWV3Vh"; httppost.setHeader(HttpHeaders.AUTHORIZATION, authHeader); httppost.setHeader(HttpHeaders.CONTENT_TYPE, "Content-Type: application/json"); Map<String, Object> params = new LinkedHashMap<>(); params.put("SERVICE", "customer.get"); JSONObject json = new JSONObject(); json.put("SERVICE", "customer.get"); //Map<String, Object> params2 = new LinkedHashMap<>(); //params2.put("CUSTOMER_NUMBER","5"); JSONObject array = new JSONObject(); array.put("CUSTOMER_NUMBER", "2"); json.put("FILTER", array); StringEntity param = new StringEntity(json.toString()); httppost.setEntity(param);/* www . j av a 2 s . com*/ HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); System.out.println("The status code is " + statusCode); //Execute and get the response. HttpEntity entity = response.getEntity(); Header[] headers = response.getAllHeaders(); for (Header header : headers) { System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue()); } if (entity != null) { String retSrc = EntityUtils.toString(entity); //Discouraged better open a stream and read the data as per Apache manual // parsing JSON //JSONObject result = new JSONObject(retSrc); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(retSrc); String prettyJsonString = gson.toJson(je); System.out.println(prettyJsonString); } //if (entity != null) { // InputStream instream = entity.getContent(); // try { // final BufferedReader reader = new BufferedReader( // new InputStreamReader(instream)); // String line = null; // while ((line = reader.readLine()) != null) { // System.out.println(line); // } // reader.close(); // } finally { // instream.close(); // } //} }
From source file:org.wso2.api.client.APIDownloader.java
public static void main(String[] args) throws Exception { String adminCookie;/*from ww w.j a v a 2 s .c om*/ String authenticationAdminURL = APIDownloaderConstant.SERVICE_URL + APIDownloaderConstant.AUTHENTICATION_ADMIN; String tenantAdminURL = APIDownloaderConstant.SERVICE_URL + APIDownloaderConstant.TENANT_ADMIN; // setting the system properties for javax.net.ssl AuthenticationAdminServiceClient.setSystemProperties(APIDownloaderConstant.CLIENT_TRUST_STORE_PATH, APIDownloaderConstant.KEY_STORE_TYPE, APIDownloaderConstant.KEY_STORE_PASSWORD); AuthenticationAdminServiceClient.init(authenticationAdminURL); log.info("retrieving the admin cookie from the logged in session...."); adminCookie = AuthenticationAdminServiceClient.login(APIDownloaderConstant.HOST_NAME, APIDownloaderConstant.USER_NAME, APIDownloaderConstant.PASSWORD); List<String> tenantDomainList = null; if (adminCookie != null) { log.info("logged in to the back-end server successfully...."); TenantMgtAdminServiceClient.init(tenantAdminURL, adminCookie); tenantDomainList = TenantMgtAdminServiceClient.getAllTenants(); } else { throw new APIStoreInvocationException("Login Failed to Admin service"); } httpClient = HttpClientBuilder.create().build(); String storeCookie = StoreAPIInvoker.loginToStore(httpClient); if (storeCookie == null) { throw new APIStoreInvocationException("Login Failed to API Store"); } for (int i = 0; i < tenantDomainList.size(); i++) { APIMetaData apiMetaData = StoreAPIInvoker.fetchAPIMetaData(httpClient, tenantDomainList.get(i), storeCookie); StoreAPIInvoker.fetchAPIDefinition(httpClient, apiMetaData, storeCookie); } }
From source file:OpenDataExtractor.java
public static void main(String[] args) { System.out.println("\nSeleziona in che campo fare la ricerca: "); System.out.println("Elenco completo delle gare in formato (1)"); // cc16106a-1a65-4c34-af13-cc045d181452 System.out.println("Composizione delle commissioni giudicatrici (2)"); // c90f1ffb-c315-4f59-b0e3-b0f2f8709127 System.out.println("Registro delle imprese escluse dalle gare (3)"); // 2ea798cc-1f52-4fc8-a28e-f92a6f409cb8 System.out.println("Registro delle imprese invitate alle gare (4)"); // a124b6af-ae31-428a-8ac5-bb341feb3c46 System.out.println("Registro delle imprese che hanno partecipato alle gare (5)");// e58396cf-1145-4cb1-84a4-34311238a0c6 System.out.println("Anagrafica completa dei contratti per l'acquisizione di beni e servizi (6)"); // aa6a8664-5ef5-43eb-a563-910e25161798 System.out.println("Fornitori (7)"); // 253c8ac9-8335-4425-84c5-4a90be863c00 System.out.println("Autorizzazioni subappalti per i lavori (8)"); // 4f9ba542-5768-4b39-a92a-450c45eabd5d System.out.println("Aggiudicazioni delle gare per i lavori (9)"); // 34e298ad-3a99-4feb-9614-b9c4071b9d8e System.out.println("Dati cruscotto lavori per area (10)"); // 1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8 System.out.println("Dati cruscotto lavori per lotto (11)"); // cbededce-269f-48d2-8c25-2359bf246f42 int count = 0; int scelta;// w w w .j av a 2s . c o m String id_ref = ""; Scanner scanner; try { do { scanner = new Scanner(System.in); scelta = scanner.nextInt(); switch (scelta) { case 1: id_ref = "cc16106a-1a65-4c34-af13-cc045d181452&q="; break; case 2: id_ref = "c90f1ffb-c315-4f59-b0e3-b0f2f8709127&q="; break; case 3: id_ref = "2ea798cc-1f52-4fc8-a28e-f92a6f409cb8&q="; break; case 4: id_ref = "a124b6af-ae31-428a-8ac5-bb341feb3c46&q="; break; case 5: id_ref = "e58396cf-1145-4cb1-84a4-34311238a0c6&q="; break; case 6: id_ref = "aa6a8664-5ef5-43eb-a563-910e25161798&q="; break; case 7: id_ref = "253c8ac9-8335-4425-84c5-4a90be863c00&q="; break; case 8: id_ref = "4f9ba542-5768-4b39-a92a-450c45eabd5d&q="; break; case 9: id_ref = "34e298ad-3a99-4feb-9614-b9c4071b9d8e&q="; break; case 10: id_ref = "1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8&q="; break; case 11: id_ref = "cbededce-269f-48d2-8c25-2359bf246f42&q="; break; default: System.out.println("Numero non selezionabile"); System.out.println("Reinserisci"); break; } } while (scelta <= 0 || scelta > 11); scanner = new Scanner(System.in); System.out.println("Inserisci un parametro di ricerca: "); String record = scanner.nextLine(); String limit = "&limit=10000"; System.out.println("id di riferimento: " + id_ref); System.out.println("___________________________"); String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id=" + id_ref + record + limit; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(requestString); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String result = ""; String resline = ""; while ((resline = rd.readLine()) != null) { result += resline; } if (result != null) { JSONObject jsonObject = new JSONObject(result); JSONObject resultJson = (JSONObject) jsonObject.get("result"); JSONArray resultJsonFields = (JSONArray) resultJson.get("fields"); ArrayList<TypeFields> type = new ArrayList<TypeFields>(); TypeFields type1; JSONObject temp; while (count < resultJsonFields.length()) { temp = (JSONObject) resultJsonFields.get(count); type1 = new TypeFields(temp.getString("id"), temp.getString("type")); type.add(type1); count++; } JSONArray arr = (JSONArray) resultJson.get("records"); count = 0; while (count < arr.length()) { System.out.println("Entry numero: " + count); temp = (JSONObject) arr.get(count); for (TypeFields temp2 : type) { System.out.println(temp2.nameType + ": " + temp.get(temp2.nameType)); } count++; System.out.println("--------------------------"); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:simauthenticator.SimAuthenticator.java
/** * @param args the command line arguments *///from w w w. j a v a2 s .co m public static void main(String[] args) throws Exception { cliOpts = new Options(); cliOpts.addOption("U", "url", true, "Connection URL"); cliOpts.addOption("u", "user", true, "User name"); cliOpts.addOption("p", "password", true, "User password"); cliOpts.addOption("d", "domain", true, "Domain name"); cliOpts.addOption("v", "verbose", false, "Verbose output"); cliOpts.addOption("k", "keystore", true, "KeyStore path"); cliOpts.addOption("K", "keystorepass", true, "KeyStore password"); cliOpts.addOption("h", "help", false, "Print help info"); CommandLineParser clip = new GnuParser(); cmd = clip.parse(cliOpts, args); if (cmd.hasOption("help")) { help(); return; } else { boolean valid = init(args); if (!valid) { return; } } HttpClientContext clientContext = HttpClientContext.create(); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); char[] keystorePassword = passwk.toCharArray(); FileInputStream kfis = null; try { kfis = new FileInputStream(keyStorePath); ks.load(kfis, keystorePassword); } finally { if (kfis != null) { kfis.close(); } } SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(ks).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setSslcontext(sslContext) .setSSLSocketFactory(sslsf).setUserAgent(userAgent); ; cookieStore = new BasicCookieStore(); /* BasicClientCookie cookie = new BasicClientCookie("SIM authenticator", "Utility for getting event details"); cookie.setVersion(0); cookie.setDomain(".astelit.ukr"); cookie.setPath("/"); cookieStore.addCookie(cookie);*/ CloseableHttpClient client = httpClientBuilder.build(); try { NTCredentials creds = new NTCredentials(usern, passwu, InetAddress.getLocalHost().getHostName(), domain); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, creds); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setCookieStore(cookieStore); HttpGet httpget = new HttpGet(eventUrl); if (verbose) { System.out.println("executing request " + httpget.getRequestLine()); } HttpResponse response = client.execute(httpget, context); HttpEntity entity = response.getEntity(); HttpPost httppost = new HttpPost(eventUrl); List<Cookie> cookies = cookieStore.getCookies(); if (verbose) { System.out.println("----------------------------------------------"); System.out.println(response.getStatusLine()); System.out.print("Initial set of cookies: "); if (cookies.isEmpty()) { System.out.println("none"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("usernameInput", usern)); nvps.add(new BasicNameValuePair("passwordInput", passwu)); nvps.add(new BasicNameValuePair("domainInput", domain)); //nvps.add(new BasicNameValuePair("j_username", domain + "\\" + usern)); //nvps.add(new BasicNameValuePair("j_password", ipAddr + ";" + passwu)); if (entity != null && verbose) { System.out.println("Responce content length: " + entity.getContentLength()); } //System.out.println(EntityUtils.toString(entity)); httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse afterPostResponse = client.execute(httppost, context); HttpEntity afterPostEntity = afterPostResponse.getEntity(); cookies = cookieStore.getCookies(); if (entity != null && verbose) { System.out.println("----------------------------------------------"); System.out.println(afterPostResponse.getStatusLine()); System.out.println("Responce content length: " + afterPostEntity.getContentLength()); System.out.print("After POST set of cookies: "); if (cookies.isEmpty()) { System.out.println("none"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } System.out.println(EntityUtils.toString(afterPostEntity)); EntityUtils.consume(entity); EntityUtils.consume(afterPostEntity); } finally { client.getConnectionManager().shutdown(); } }
From source file:org.springside.examples.schedule.TransferOaDataToGx.java
public static void main(String[] args) { // /* ww w .ja v a2 s.c o m*/ // // ? // HttpPost httpPost = new HttpPost("http://gxoa.cc/login!login.do?userName=&userPassword=gxuser&loginState=1"); // // // ?connection poolclient // RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20 * 1000) // .setConnectTimeout(20 * 1000).build(); // // CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(20).setMaxConnPerRoute(20) // .setDefaultRequestConfig(requestConfig).build(); // try { // CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost); // System.out.println(IOUtils.toString(closeableHttpResponse.getEntity().getContent(), "UTF-8")); // HttpGet httpGet = new HttpGet("http://gxoa.cc/attachmentDownload.do?filePath=2010-07/2010-07-28-4bdd9279-c09e-4b68-80fc-c9d049c6bdfc-GXTC-1005124--??20091062.rar"); // CloseableHttpResponse closeableHttpResponseFile = httpClient.execute(httpGet); // //FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\")); // System.out.println(IOUtils.toString(closeableHttpResponseFile.getEntity().getContent(), "UTF-8")); // // // } catch (ClientProtocolException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // HttpPost httpPost = new HttpPost("http://219.239.33.123:9090/quickstart/api/getFileFromFTP"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("filePath", "2015-04/2015-04-28-718f376f-b725-4e18-87e2-43e30124b2b5-GXTC-1506112-&-.rar")); String salt = "GXCX_OA_SALT"; long currentTime = ((new Date().getTime() * 4 + 2) * 5 - 1) * 8 + 3;// by yucy String key = salt + currentTime; nvps.add(new BasicNameValuePair("key", Base64.encodeBase64String(key.getBytes()))); try { httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // ?connection poolclient RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20 * 1000) .setConnectTimeout(20 * 1000).build(); CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(20).setMaxConnPerRoute(20) .setDefaultRequestConfig(requestConfig).build(); try { CloseableHttpResponse closeableHttpResponseFile = httpClient.execute(httpPost); FileUtils.writeByteArrayToFile(new File("D:/upload/templateBulletin.rar"), IOUtils.toByteArray(closeableHttpResponseFile.getEntity().getContent())); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //TODO ? //FileUtils.writeByteArrayToFile( file, FileUtils.readFileToByteArray( new File("D:/upload/templateBulletin.zip") ) ); }
From source file:io.alicorn.device.client.DeviceClient.java
public static void main(String[] args) { logger.info("Starting Alicorn Client System"); // Prepare Display Color. transform3xWrite(DisplayTools.commandForColor(0, 204, 255)); // Setup text information. // transform3xWrite(DisplayTools.commandForText("Sup Fam")); class StringWrapper { public String string = ""; }/*from w w w. ja v a2 s . c om*/ final StringWrapper string = new StringWrapper(); // Text Handler. Thread thread = new Thread(new Runnable() { @Override public void run() { String latestString = ""; String outputStringLine1Complete = ""; long outputStringLine1Cursor = 1; int outputStringLine1Mask = 0; String outputStringLine2 = ""; while (true) { if (!latestString.equals(string.string)) { latestString = string.string; String[] latestStrings = latestString.split("::"); outputStringLine1Complete = latestStrings[0]; outputStringLine1Mask = outputStringLine1Complete.length(); outputStringLine1Cursor = 0; // Trim second line to a length of sixteen. outputStringLine2 = latestStrings.length > 1 ? latestStrings[1] : ""; if (outputStringLine2.length() > 16) { outputStringLine2 = outputStringLine2.substring(0, 16); } } StringBuilder outputStringLine1 = new StringBuilder(); if (outputStringLine1Complete.length() > 0) { long cursor = outputStringLine1Cursor; for (int i = 0; i < 16; i++) { outputStringLine1.append( outputStringLine1Complete.charAt((int) (cursor % outputStringLine1Mask))); cursor += 1; } outputStringLine1Cursor += 1; } else { outputStringLine1.append(" "); } try { transform3xWrite( DisplayTools.commandForText(outputStringLine1.toString() + outputStringLine2)); Thread.sleep(400); } catch (Exception e) { e.printStackTrace(); } } } }); thread.start(); // Event Handler while (true) { try { String url = "http://169.254.90.174:9789/api/iot/narwhalText"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); string.string = apacheHttpEntityToString(response.getEntity()); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.hp.autonomy.iod.client.RestAdapterFactory.java
public static RestAdapter getRestAdapter(final boolean withInterceptor, final Endpoint endpoint) { final HttpClientBuilder builder = HttpClientBuilder.create(); final String proxyHost = System.getProperty("hp.iod.https.proxyHost"); if (proxyHost != null) { final Integer proxyPort = Integer.valueOf(System.getProperty("hp.iod.https.proxyPort", "8080")); builder.setProxy(new HttpHost(proxyHost, proxyPort)); }//from w w w . ja v a 2 s .c o m final RestAdapter.Builder restAdapterBuilder = new RestAdapter.Builder().setEndpoint(endpoint.getUrl()) .setClient(new ApacheClient(builder.build())).setConverter(new IodConverter()) .setErrorHandler(new IodErrorHandler()); if (withInterceptor) { restAdapterBuilder.setRequestInterceptor(new ApiKeyRequestInterceptor(endpoint.getApiKey())); } return restAdapterBuilder.build(); }
From source file:com.hp.autonomy.hod.client.HodServiceConfigFactory.java
public static HodServiceConfig<EntityType.Application, TokenType.Simple> getHodServiceConfig( final TokenProxyService<EntityType.Application, TokenType.Simple> tokenProxyService, final Endpoint endpoint) { final HttpClientBuilder builder = HttpClientBuilder.create(); builder.disableCookieManagement();//from w ww . j av a2s. c o m builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60000).build()); final String proxyHost = System.getProperty("hp.hod.https.proxyHost"); if (proxyHost != null) { final Integer proxyPort = Integer.valueOf(System.getProperty("hp.hod.https.proxyPort", "8080")); builder.setProxy(new HttpHost(proxyHost, proxyPort)); } final HodServiceConfig.Builder<EntityType.Application, TokenType.Simple> configBuilder = new HodServiceConfig.Builder<EntityType.Application, TokenType.Simple>( endpoint.getUrl()).setHttpClient(builder.build()); if (tokenProxyService != null) { configBuilder.setTokenProxyService(tokenProxyService); } return configBuilder.build(); }
From source file:coolmapplugin.util.HTTPRequestUtil.java
public static String executePost(String targetURL, String jsonBody) { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost request = new HttpPost(targetURL); StringEntity params = new StringEntity(jsonBody); request.addHeader("content-type", "application/json"); request.setEntity(params);// www . j a v a2 s .com HttpResponse result = httpClient.execute(request); HttpEntity entity = result.getEntity(); if (entity == null) return null; String jsonResult = EntityUtils.toString(result.getEntity(), "UTF-8"); return jsonResult; } catch (IOException e) { return null; } }