List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.edgenius.wiki.Shell.java
/** * Please note, this method doesn't reset current Shell.key. If this request failed, the original Shell.key value is still remained. * @return//from ww w . ja va2 s .c om */ public static boolean requestInstanceShellKey() { try { log.info("Request shell key for current instance"); //reset last keyValidator value - will use new one. keyValidator = null; HttpURLConnection conn = (HttpURLConnection) new URL( getShellURL(Installation.INSTANCE_ID, null, null, false, null, false)).openConnection(); //as instance key request is important, so we extends its timeout as original 2 times. conn.setConnectTimeout(timeout * 2); InputStream is = conn.getInputStream(); ByteArrayOutputStream writer = new ByteArrayOutputStream(); int len; byte[] bytes = new byte[200]; while ((len = is.read(bytes)) != -1) { writer.write(bytes, 0, len); } String response = new String(writer.toByteArray()); //see GShell project, ShellServlet response for instance //Here return is MD5 of key value.... if (response.startsWith("KEY-VALIDATOR:")) { lock.lock(); try { keyValidator = response.substring(14).trim(); if (!keyValidCondition.await(timeout * 2, TimeUnit.MILLISECONDS)) { log.error("Unable to get valid Shell request for key. Request Instance shell key failed."); keyValidator = null; return false; } //here, suppose shell key is already fill in. return !StringUtils.isEmpty(Shell.key); } finally { lock.unlock(); } } //suspect current thread to wait until key valid } catch (IOException e) { log.error("Unable to connect shell for notification", e); } catch (Throwable e) { log.error("Notify shell failure", e); } return false; }
From source file:loadTest.loadTestLib.LUtil.java
public static boolean startDockerBuild() throws IOException, InterruptedException { if (useDocker) { if (runInDockerCluster) { HashMap<String, Integer> dockerNodes = getDockerNodes(); String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString() .substring(5);/*ww w . ja v a 2 s. co m*/ ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size()); dockerError = false; doneDockers = 0; for (Entry<String, Integer> entry : dockerNodes.entrySet()) { exec.submit(new Runnable() { @Override public void run() { try { String url = entry.getKey() + "/images/vauvenal5/loadtest"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("DELETE"); con.setRequestProperty("force", "true"); int responseCode = con.getResponseCode(); con.disconnect(); url = entry.getKey() + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile"; obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/tar"); con.setDoOutput(true); File file = new File(dockerTar); FileInputStream fileStr = new FileInputStream(file); byte[] b = new byte[(int) file.length()]; fileStr.read(b); con.getOutputStream().write(b); con.getOutputStream().flush(); con.getOutputStream().close(); responseCode = con.getResponseCode(); if (responseCode != 200) { dockerError = true; } String msg = ""; do { Thread.sleep(5000); msg = ""; url = entry.getKey() + "/images/json"; obj = new URL(url); HttpURLConnection con2 = (HttpURLConnection) obj.openConnection(); con2.setRequestMethod("GET"); responseCode = con2.getResponseCode(); BufferedReader in = new BufferedReader( new InputStreamReader(con2.getInputStream())); String line = null; while ((line = in.readLine()) != null) { msg += line; } con2.disconnect(); } while (!msg.contains("vauvenal5/loadtest")); con.disconnect(); doneDockers++; } catch (MalformedURLException ex) { dockerError = true; } catch (FileNotFoundException ex) { dockerError = true; } catch (IOException ex) { dockerError = true; } catch (InterruptedException ex) { dockerError = true; } } }); } while (doneDockers < dockerNodes.size()) { Thread.sleep(5000); } return !dockerError; } //get the path and substring the 'file:' from the URI String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5); ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest"); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process docker = processBuilder.start(); docker.waitFor(); processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process proc = processBuilder.start(); return proc.waitFor() == 0; } return true; }
From source file:com.gmobi.poponews.util.HttpHelper.java
public static int download(String url, File file) { HttpURLConnection connection = null; int length = 0; try {/*from ww w . ja va2 s . c o m*/ URL httpURL = new URL(url); connection = (HttpURLConnection) httpURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); length = connection.getContentLength(); FileHelper.copy(connection.getInputStream(), file); connection = null; } catch (Exception e) { Logger.error(e); } return length; }
From source file:com.fluidops.iwb.luxid.LuxidExtractor.java
public static String authenticate() throws Exception { String token = ""; /* ***** Authentication ****** */ String auth = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP-ENV:Body> <ns1:authenticate xmlns:ns1=\"http://luxid.temis.com/ws/types\"> " + "<ns1:userName>" + Config.getConfig().getLuxidUserName() + "</ns1:userName> <ns1:userPassword>" + Config.getConfig().getLuxidPassword() + "</ns1:userPassword> </ns1:authenticate> </SOAP-ENV:Body> </SOAP-ENV:Envelope>"; URL authURL = new URL(Config.getConfig().getLuxidServerURL()); HttpURLConnection authconn = (HttpURLConnection) authURL.openConnection(); authconn.setRequestMethod("POST"); authconn.setDoOutput(true);/* ww w. j a va2s . com*/ authconn.getOutputStream().write(auth.getBytes()); if (authconn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream stream = authconn.getInputStream(); InputStreamReader read = new InputStreamReader(stream); BufferedReader rd = new BufferedReader(read); String line = ""; if ((line = rd.readLine()) != null) { token = line.substring(line.indexOf("<token>") + "<token>".length(), line.indexOf("</token>")); } rd.close(); } return token; }
From source file:com.andrew.apollo.cache.ImageFetcher.java
/** * Download a {@link Bitmap} from a URL, write it to a disk and return the * File pointer. This implementation uses a simple disk cache. * * @param context The context to use//from w w w.j av a 2s .c o m * @param urlString The URL to fetch * @return A {@link File} pointing to the fetched bitmap */ public static final File downloadBitmapToFile(final Context context, final String urlString, final String uniqueName) { final File cacheDir = ImageCache.getDiskCacheDir(context, uniqueName); if (!cacheDir.exists()) { cacheDir.mkdir(); } HttpURLConnection urlConnection = null; BufferedOutputStream out = null; try { final File tempFile = File.createTempFile("bitmap", null, cacheDir); //$NON-NLS-1$ final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } final InputStream in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES); out = new BufferedOutputStream(new FileOutputStream(tempFile), IO_BUFFER_SIZE_BYTES); int oneByte; while ((oneByte = in.read()) != -1) { out.write(oneByte); } return tempFile; } catch (final IOException ignored) { ignored.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (out != null) { try { out.close(); } catch (final IOException ignored) { } } } return null; }
From source file:com.grosscommerce.ICEcat.utilities.Downloader.java
public static void download(String urlFrom, String login, String pwd, OutputStream destStream) throws Exception { try {/*from w w w . jav a 2s .c o m*/ HttpURLConnection uc = prepareConnection(urlFrom, login, pwd); uc.connect(); if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) { Logger.getLogger(Downloader.class.getName()).log(Level.INFO, "Error, code: {0}, message {1}", new Object[] { uc.getResponseCode(), uc.getResponseMessage() }); return; } BufferedInputStream is = null; if ((uc.getContentEncoding() != null && uc.getContentEncoding().toLowerCase().equals("gzip")) || uc.getContentType() != null && uc.getContentType().toLowerCase().contains("gzip")) { is = new BufferedInputStream(new GZIPInputStream(uc.getInputStream())); Logger.getLogger(Downloader.class.getName()).log(Level.INFO, "Will download gzip data from: {0}", urlFrom); } else { is = new BufferedInputStream(uc.getInputStream()); Logger.getLogger(Downloader.class.getName()).log(Level.INFO, "Will download not compressed data from:{0}", urlFrom); } StreamsHelper.copy(is, destStream); destStream.flush(); } catch (Exception ex) { Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, "URL: " + urlFrom, ex); throw ex; } }
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
public static int post(String url, JSONObject json, String username, String password) throws IOException { HttpURLConnection conn = createConnection(url, username, password); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "application/json"); byte[] jsonBytes = json.toString().getBytes("UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(jsonBytes.length)); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(jsonBytes);//from ww w .j a v a2 s .c o m out.flush(); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048); for (String line = reader.readLine(); line != null; line = reader.readLine()) { } out.close(); int responseCode = 0; responseCode = conn.getResponseCode(); return responseCode; }
From source file:com.example.igorklimov.popularmoviesdemo.helpers.Utility.java
public static String getJsonResponse(String s) { HttpURLConnection connection = null; InputStream input = null;/*w ww . j av a 2 s . c om*/ BufferedReader reader = null; String JsonResponse = null; try { URL url = new URL(s); Log.d("TAG", url.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); input = connection.getInputStream(); StringBuilder builder = new StringBuilder(); if (input != null) { reader = new BufferedReader(new InputStreamReader(input)); String line; while ((line = reader.readLine()) != null) { builder.append(line).append("\n"); } JsonResponse = builder.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return JsonResponse; }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
public static String get(String endpoint) { URL url = null;//w w w.jav a 2 s .c om try { url = new URL(endpoint); } catch (MalformedURLException e) { //Fail silently } HttpURLConnection conn; long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); for (int i = 1; i <= HttpUtilities.MAX_ATTEMPTS; i++) { try { conn = makeGetConnection(url); // handle the response int status = conn.getResponseCode(); if (status == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); if (null != conn) { conn.disconnect(); } return sb.toString(); } else if (500 > status) { if (null != conn) { conn.disconnect(); } return null; } } catch (IOException e) { try { Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Thread.currentThread().interrupt(); } // increase backoff exponentially backoff *= 2; } } return null; }
From source file:a122016.rr.com.alertme.QueryUtilsPoliceStation.java
/** * Make an HTTP request to the given URL and return a String as the response. *//*ww w. jav a2 s .c o m*/ private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the PoliceStations JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { // Closing the input stream could throw an IOException, which is why // the makeHttpRequest(URL url) method signature specifies than an IOException // could be thrown. inputStream.close(); } } return jsonResponse; }