List of usage examples for org.apache.http.client.methods HttpGet HttpGet
public HttpGet(final String uri)
From source file:eu.prestoprime.p4gui.connection.P4HttpClient.java
public static void main(String[] args) throws Exception { P4HttpClient client = new P4HttpClient("pr3st0.2012"); HttpGet request = new HttpGet( "http://p4.eurixgroup.com/p4ws/search/quick?createDateFacet=%5B2012-08-02T00%3A00%3A00Z+TO+2012-08-02T00%3A00%3A00Z%2B7DAY%5D&publisherFacet=&sortAsc=true&sortField=titleSort&waisdaFacet=&term=&resultCount=&dateFacet=&from=&creatorFacet="); client.executeRequest(request);//from w w w . ja va 2 s .c om }
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 = ""; }// w w w . jav a 2s .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:co.paralleluniverse.photon.Photon.java
public static void main(final String[] args) throws InterruptedException, IOException { final Options options = new Options(); options.addOption("rate", true, "Requests per second (default " + rateDefault + ")"); options.addOption("duration", true, "Minimum test duration in seconds: will wait for <duration> * <rate> requests to terminate or, if progress check enabled, no progress after <duration> (default " + durationDefault + ")"); options.addOption("maxconnections", true, "Maximum number of open connections (default " + maxConnectionsDefault + ")"); options.addOption("timeout", true, "Connection and read timeout in millis (default " + timeoutDefault + ")"); options.addOption("print", true, "Print cycle in millis, 0 to disable intermediate statistics (default " + printCycleDefault + ")"); options.addOption("check", true, "Progress check cycle in millis, 0 to disable progress check (default " + checkCycleDefault + ")"); options.addOption("stats", false, "Print full statistics when finish (default false)"); options.addOption("minmax", false, "Print min/mean/stddev/max stats when finish (default false)"); options.addOption("name", true, "Test name to print in the statistics (default '" + testNameDefault + "')"); options.addOption("help", false, "Print help"); try {//from ww w. ja va2 s . com final CommandLine cmd = new BasicParser().parse(options, args); final String[] ar = cmd.getArgs(); if (cmd.hasOption("help") || ar.length != 1) printUsageAndExit(options); final String url = ar[0]; final int timeout = Integer.parseInt(cmd.getOptionValue("timeout", timeoutDefault)); final int maxConnections = Integer .parseInt(cmd.getOptionValue("maxconnections", maxConnectionsDefault)); final int duration = Integer.parseInt(cmd.getOptionValue("duration", durationDefault)); final int printCycle = Integer.parseInt(cmd.getOptionValue("print", printCycleDefault)); final int checkCycle = Integer.parseInt(cmd.getOptionValue("check", checkCycleDefault)); final String testName = cmd.getOptionValue("name", testNameDefault); final int rate = Integer.parseInt(cmd.getOptionValue("rate", rateDefault)); final MetricRegistry metrics = new MetricRegistry(); final Meter requestMeter = metrics.meter("request"); final Meter responseMeter = metrics.meter("response"); final Meter errorsMeter = metrics.meter("errors"); final Logger log = LoggerFactory.getLogger(Photon.class); final ConcurrentHashMap<String, AtomicInteger> errors = new ConcurrentHashMap<>(); final HttpGet request = new HttpGet(url); final StripedTimeSeries<Long> sts = new StripedTimeSeries<>(30000, false); final StripedHistogram sh = new StripedHistogram(60000, 5); log.info("name: " + testName + " url:" + url + " rate:" + rate + " duration:" + duration + " maxconnections:" + maxConnections + ", " + "timeout:" + timeout); final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom() .setConnectTimeout(timeout).setIoThreadCount(10).setSoTimeout(timeout).build()); Runtime.getRuntime().addShutdownHook(new Thread(() -> { final List<ExceptionEvent> events = ioreactor.getAuditLog(); if (events != null) events.stream().filter(event -> event != null).forEach(event -> { System.err.println( "Apache Async HTTP Client I/O Reactor Error Time: " + event.getTimestamp()); //noinspection ThrowableResultOfMethodCallIgnored if (event.getCause() != null) //noinspection ThrowableResultOfMethodCallIgnored event.getCause().printStackTrace(); }); if (cmd.hasOption("stats")) printFinishStatistics(errorsMeter, sts, sh, testName); if (!errors.keySet().isEmpty()) errors.entrySet().stream() .forEach(p -> log.info(testName + " " + p.getKey() + " " + p.getValue() + "ms")); System.out.println( testName + " responseTime(90%): " + sh.getHistogramData().getValueAtPercentile(90) + "ms"); if (cmd.hasOption("minmax")) { final HistogramData hd = sh.getHistogramData(); System.out.format("%s %8s%8s%8s%8s\n", testName, "min", "mean", "sd", "max"); System.out.format("%s %8d%8.2f%8.2f%8d\n", testName, hd.getMinValue(), hd.getMean(), hd.getStdDeviation(), hd.getMaxValue()); } })); final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor); mngr.setDefaultMaxPerRoute(maxConnections); mngr.setMaxTotal(maxConnections); final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().setConnectionManager(mngr) .setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build(); try (final CloseableHttpClient client = new FiberHttpClient(ahc)) { final int num = duration * rate; final CountDownLatch cdl = new CountDownLatch(num); final Semaphore sem = new Semaphore(maxConnections); final RateLimiter rl = RateLimiter.create(rate); spawnStatisticsThread(printCycle, cdl, log, requestMeter, responseMeter, errorsMeter, testName); for (int i = 0; i < num; i++) { rl.acquire(); if (sem.availablePermits() == 0) log.debug("Maximum connections count reached, waiting..."); sem.acquireUninterruptibly(); new Fiber<Void>(() -> { requestMeter.mark(); final long start = System.nanoTime(); try { try (final CloseableHttpResponse ignored = client.execute(request)) { responseMeter.mark(); } catch (final Throwable t) { markError(errorsMeter, errors, t); } } catch (final Throwable t) { markError(errorsMeter, errors, t); } finally { final long now = System.nanoTime(); final long millis = TimeUnit.NANOSECONDS.toMillis(now - start); sts.record(start, millis); sh.recordValue(millis); sem.release(); cdl.countDown(); } }).start(); } spawnProgressCheckThread(log, duration, checkCycle, cdl); cdl.await(); } } catch (final ParseException ex) { System.err.println("Parsing failed. Reason: " + ex.getMessage()); } }
From source file:simauthenticator.SimAuthenticator.java
/** * @param args the command line arguments *///from ww w.j a v a2 s .c o 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:net.modelbased.proasense.storage.reader.StorageReaderMongoServiceRestBenchmark.java
public static void main(String[] args) { // Get benchmark properties StorageReaderMongoServiceRestBenchmark benchmark = new StorageReaderMongoServiceRestBenchmark(); benchmark.loadClientProperties();//from w w w . j a v a 2 s. co m // ProaSense Storage Reader Service configuration properties String STORAGE_READER_SERVICE_URL = benchmark.clientProperties .getProperty("proasense.storage.reader.service.url"); String QUERY_SIMPLE_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.collectionid"); String NO_QUERY_SIMPLE_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.starttime"); String NO_QUERY_SIMPLE_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.endtime"); String QUERY_DERIVED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.collectionid"); String NO_QUERY_DERIVED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.starttime"); String NO_QUERY_DERIVED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.endtime"); String QUERY_PREDICTED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.collectionid"); String NO_QUERY_PREDICTED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.starttime"); String NO_QUERY_PREDICTED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.endtime"); String QUERY_ANOMALY_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.collectionid"); String NO_QUERY_ANOMALY_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.starttime"); String NO_QUERY_ANOMALY_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.endtime"); String QUERY_RECOMMENDATION_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.collectionid"); String NO_QUERY_RECOMMENDATION_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.starttime"); String NO_QUERY_RECOMMENDATION_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.endtime"); String QUERY_FEEDBACK_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.collectionid"); String NO_QUERY_FEEDBACK_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.starttime"); String NO_QUERY_FEEDBACK_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.endtime"); String propertyKey = "value"; // Default HTTP client and common property variables for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null; StatusLine status = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); try { status = client.execute(query11).getStatusLine(); System.out.println("SIMPLE.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/value"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", "value")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query12 = new HttpGet(STORAGE_READER_SERVICE_URL); query12.setHeader("Content-type", "application/json"); try { status = client.execute(query12).getStatusLine(); System.out.println("SIMPLE.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events HttpGet query13 = new HttpGet(STORAGE_READER_SERVICE_URL); query13.setHeader("Content-type", "application/json"); try { status = client.execute(query13).getStatusLine(); System.out.println("SIMPLE.MAXIMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events HttpGet query14 = new HttpGet(STORAGE_READER_SERVICE_URL); query14.setHeader("Content-type", "application/json"); try { status = client.execute(query14).getStatusLine(); System.out.println("SIMPLE.MINUMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for derived events HttpGet query21 = new HttpGet(STORAGE_READER_SERVICE_URL); query21.setHeader("Content-type", "application/json"); try { status = client.execute(query21).getStatusLine(); System.out.println("DERIVED.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for derived events HttpGet query22 = new HttpGet(STORAGE_READER_SERVICE_URL); query22.setHeader("Content-type", "application/json"); try { status = client.execute(query22).getStatusLine(); System.out.println("DERIVED.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query23 = new HttpGet(STORAGE_READER_SERVICE_URL); query23.setHeader("Content-type", "application/json"); try { status = client.execute(query23).getStatusLine(); System.out.println("DERIVED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query24 = new HttpGet(STORAGE_READER_SERVICE_URL); query24.setHeader("Content-type", "application/json"); try { status = client.execute(query24).getStatusLine(); System.out.println("DERIVED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for predicted events HttpGet query31 = new HttpGet(STORAGE_READER_SERVICE_URL); query31.setHeader("Content-type", "application/json"); try { status = client.execute(query31).getStatusLine(); System.out.println("PREDICTED.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for predicted events HttpGet query32 = new HttpGet(STORAGE_READER_SERVICE_URL); query32.setHeader("Content-type", "application/json"); try { status = client.execute(query32).getStatusLine(); System.out.println("PREDICTED.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for predicted events HttpGet query33 = new HttpGet(STORAGE_READER_SERVICE_URL); query33.setHeader("Content-type", "application/json"); try { status = client.execute(query33).getStatusLine(); System.out.println("PREDICTED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query34 = new HttpGet(STORAGE_READER_SERVICE_URL); query34.setHeader("Content-type", "application/json"); try { status = client.execute(query34).getStatusLine(); System.out.println("PREDICTED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for anomaly events HttpGet query41 = new HttpGet(STORAGE_READER_SERVICE_URL); query41.setHeader("Content-type", "application/json"); try { status = client.execute(query41).getStatusLine(); System.out.println("ANOMALY.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for recommendation events HttpGet query51 = new HttpGet(STORAGE_READER_SERVICE_URL); query51.setHeader("Content-type", "application/json"); try { status = client.execute(query51).getStatusLine(); System.out.println("RECOMMENDATION.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for recommendation events HttpGet query52 = new HttpGet(STORAGE_READER_SERVICE_URL); query52.setHeader("Content-type", "application/json"); try { status = client.execute(query52).getStatusLine(); System.out.println("RECOMMENDATION.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query53 = new HttpGet(STORAGE_READER_SERVICE_URL); query53.setHeader("Content-type", "application/json"); try { status = client.execute(query53).getStatusLine(); System.out.println("RECOMMENDATION.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query54 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("RECOMMENDATION.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for feedback events HttpGet query61 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("FEEDBACK.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.astrientlabs.nyt.NYT.java
public static void main(String[] args) { try {/*from w w w . j a v a2s. co m*/ int session = 112; MembersResponse r = NYT.instance.getMembers(session, NYT.Branch.Senate, null, null); Member[] members = r.getItems(); if (members != null) { String imgUrl; File dir = new File("/Users/rashidmayes/tmp/nyt/", String.valueOf(session)); dir.mkdirs(); File outDir; File outFile; for (Member member : members) { System.out.println(member); imgUrl = NYT.instance.extractImageURL(session, member); System.out.println(imgUrl); if (imgUrl != null) { try { HttpClient httpclient = new DefaultHttpClient(); HttpGet get = new HttpGet(imgUrl); HttpResponse response = httpclient.execute(get); if (response.getStatusLine().getStatusCode() == 200) { outDir = new File(dir, member.getId()); outDir.mkdirs(); outFile = new File(outDir, (member.getFirst_name() + "." + member.getLast_name() + ".jpg") .toLowerCase()); FileOutputStream fos = null; try { fos = new FileOutputStream(outFile); response.getEntity().writeTo(fos); } finally { if (fos != null) { fos.close(); } } } } catch (Exception e) { e.printStackTrace(); } } } } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.exit(0); }
From source file:ClientConfiguration.java
public final static void main(String[] args) throws Exception { // Use custom message parser / writer to customize the way HTTP messages are parsed from and written out to the data stream. HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() { @Override/* w w w . j a v a 2 s. c om*/ public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer, MessageConstraints constraints) { LineParser lineParser = new BasicLineParser() { @Override public Header parseHeader(final CharArrayBuffer buffer) { try { return super.parseHeader(buffer); } catch (ParseException ex) { return new BasicHeader(buffer.toString(), null); } } }; return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) { @Override protected boolean reject(final CharArrayBuffer line, int count) { // try to ignore all garbage preceding a status line infinitely return false; } }; } }; HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory(); // Use a custom connection factory to customize the process of initialization of outgoing HTTP connections. // Beside standard connection configuration parameters HTTP connection factory can define message parser / writer routines to be employed by individual connections. HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory( requestWriterFactory, responseParserFactory); // Client HTTP connection objects when fully initialized can be bound to an arbitrary network socket. // The process of network socket initialization, // its connection to a remote address and binding to a local one is controlled by a connection socket factory. // SSL context for secure connections can be created either based on // system or application specific properties. SSLContext sslcontext = SSLContexts.createSystemDefault(); // Use custom hostname verifier to customize SSL hostname verification. X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build(); // Use custom DNS resolver to override the system DNS resolution. DnsResolver dnsResolver = new SystemDefaultDnsResolver() { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } }; // Create a connection manager with custom configuration. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry, connFactory, dnsResolver); // Create socket configuration SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); // Configure the connection manager to use socket configuration either // by default or for a specific host. connManager.setDefaultSocketConfig(socketConfig); connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig); // Create message constraints MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); // Create connection configuration ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints).build(); // Configure the connection manager to use connection configuration either // by default or for a specific host. connManager.setDefaultConnectionConfig(connectionConfig); connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); // Configure total max or per route limits for persistent connections // that can be kept in the pool or leased by the connection manager. connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(10); connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); // Use custom cookie store if necessary. CookieStore cookieStore = new BasicCookieStore(); // Use custom credentials provider if necessary. CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // Create global request configuration RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build(); // Create an HttpClient with the given custom dependencies and configuration. CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager) .setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider) .setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build(); try { HttpGet httpget = new HttpGet("http://www.apache.org/"); // Request configuration can be overridden at the request level. // They will take precedence over the one set at the client level. RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000) .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setProxy(new HttpHost("myotherproxy", 8080)).build(); httpget.setConfig(requestConfig); // Execution context can be customized locally. HttpClientContext context = HttpClientContext.create(); // Contextual attributes set the local context level will take // precedence over those set at the client level. context.setCookieStore(cookieStore); context.setCredentialsProvider(credentialsProvider); System.out.println("executing request " + httpget.getURI()); CloseableHttpResponse response = httpclient.execute(httpget, context); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } System.out.println("----------------------------------------"); // Once the request has been executed the local context can // be used to examine updated state and various objects affected // by the request execution. // Last executed request context.getRequest(); // Execution route context.getHttpRoute(); // Target auth state context.getTargetAuthState(); // Proxy auth state context.getTargetAuthState(); // Cookie origin context.getCookieOrigin(); // Cookie spec used context.getCookieSpec(); // User security token context.getUserToken(); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:Main.java
public static HttpGet getHttpGet(String url) { HttpGet request = new HttpGet(url); return request; }
From source file:Main.java
private static HttpGet getHttpGet(String url) { HttpGet httpGet = new HttpGet(url); return httpGet; }
From source file:com.emc.cto.ridagent.rid.test.TestScript.java
public static void main(String args[]) throws SAXException, ParserConfigurationException, URISyntaxException, ClientProtocolException, IOException { String xmlData = " <iodef-rid:RID lang=\"en\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:iodef-rid=\"urn:ietf:params:xml:ns:iodef-rid-2.0\" xmlns:iodef=\"urn:ietf:params:xml:ns:iodef-1.42\" xsi:schemaLocation=\"urn:ietf:params:xml:ns:iodef-rid-2.0 iodef-rid-2.0.xsd\">"; xmlData = xmlData + "<iodef-rid:RIDPolicy MsgType=\"Report\" MsgDestination=\"RIDSystem\">"; xmlData = xmlData + "<iodef-rid:PolicyRegion region=\"IntraConsortium\"/>"; xmlData = xmlData + " <iodef:Node>"; xmlData = xmlData + " <iodef:NodeName>192.168.1.1</iodef:NodeName>"; xmlData = xmlData + " </iodef:Node>"; xmlData = xmlData + "<iodef-rid:TrafficType type=\"Network\"/>"; xmlData = xmlData + "</iodef-rid:RIDPolicy>"; xmlData = xmlData + "</iodef-rid:RID>"; String id = TestScript.httpSend(xmlData, "https://ridtest.emc.com:4590/"); HttpGet httpget = new HttpGet("http://localhost:1280/federation/RID/" + id + "/report.xml"); DefaultHttpClient httpclient = new DefaultHttpClient(); Credentials defaultcreds = new UsernamePasswordCredentials("Administrator", "secret"); httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), defaultcreds);/*from w ww.ja va 2 s . c o m*/ httpget.setHeader("User-Agent", "EMC RID System"); HttpResponse response = httpclient.execute(httpget); if (response.getEntity() != null) { int code = response.getStatusLine().getStatusCode(); if (code == 404) { System.out.println("Error has occured! Document not found in the xDB"); } else if (code == 200) { System.out.println("Document Successfully saved in the database"); } else { System.out.println("Error could not be determined"); } } }