List of usage examples for java.net URLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.varaneckas.hawkscope.Version.java
/** * Asynchroniously checks if a newer version of Hawkscope is available * /*from w w w . j ava 2 s. com*/ * @return */ public static void checkForUpdate() { if (!cfg.checkForUpdates()) { return; } try { log.debug("Checking for updates..."); URLConnection conn = null; final URL versionCheckUrl = new URL(VERSION_CHECK_URL); Proxy proxy = null; if (cfg.isHttpProxyInUse()) { proxy = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(cfg.getHttpProxyHost(), cfg.getHttpProxyPort())); conn = versionCheckUrl.openConnection(proxy); } else { conn = versionCheckUrl.openConnection(); } conn.setConnectTimeout(Constants.CONNECTION_TIMOUT); conn.setReadTimeout(Constants.CONNECTION_TIMOUT); final InputStream io = conn.getInputStream(); int c = 0; final StringBuilder version = new StringBuilder(); while ((c = io.read()) != -1) { version.append((char) c); } if (log.isDebugEnabled()) { log.debug("Check complete. Latest " + OSUtils.CURRENT_OS + " version: " + version.toString()); } if (VERSION_NUMBER.compareTo(version.toString()) < 0) { log.info("Newer " + OSUtils.CURRENT_OS + " version available (" + version.toString() + "). You should update Hawkscope!"); isUpdateAvailable = true; updateVersion = version.toString(); } else { log.info("You have the latest available version of Hawkscope: " + VERSION_NUMBER); isUpdateAvailable = false; } PluginManager.getInstance().checkPluginUpdates(PLUGIN_VERSION_CHECK_URL, proxy); } catch (final Exception e) { log.info("Failed checking for update: " + e.getMessage()); } }
From source file:com.simiacryptus.util.Util.java
/** * Get input stream./* ww w. j ava2s. co m*/ * * @param url the url * @return the input stream * @throws NoSuchAlgorithmException the no such algorithm exception * @throws KeyManagementException the key management exception * @throws IOException the io exception */ public static InputStream get(@javax.annotation.Nonnull String url) throws NoSuchAlgorithmException, KeyManagementException, IOException { @javax.annotation.Nonnull final TrustManager[] trustManagers = { new X509TrustManager() { @Override public void checkClientTrusted(final X509Certificate[] certs, final String authType) { } @Override public void checkServerTrusted(final X509Certificate[] certs, final String authType) { } @javax.annotation.Nonnull @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; @javax.annotation.Nonnull final SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, trustManagers, null); final SSLSocketFactory sslFactory = ctx.getSocketFactory(); final URLConnection urlConnection = new URL(url).openConnection(); if (urlConnection instanceof HttpsURLConnection) { @javax.annotation.Nonnull final HttpsURLConnection conn = (HttpsURLConnection) urlConnection; conn.setSSLSocketFactory(sslFactory); conn.setRequestMethod("GET"); } return urlConnection.getInputStream(); }
From source file:com.android.W3T.app.network.NetworkUtil.java
public static String attemptSearch(String op, int range, String[] terms) { // Here we may want to check the network status. checkNetwork();/*from w ww . j a v a 2 s . c o m*/ try { JSONObject param = new JSONObject(); param.put("acc", UserProfile.getUsername()); param.put("opcode", "search"); param.put("mobile", true); JSONObject jsonstr = new JSONObject(); if (op == METHOD_KEY_SEARCH) { // Add your data // Add keys if there is any. if (terms != null) { JSONArray keys = new JSONArray(); int numTerm = terms.length; for (int i = 0; i < numTerm; i++) { keys.put(terms[i]); } param.put("keys", keys); } // Calculate the Search Range by last N days Calendar c = Calendar.getInstance(); if (range == -SEVEN_DAYS || range == -FOURTEEN_DAYS) { // 7 days or 14 days c.add(Calendar.DAY_OF_MONTH, range); } else if (range == -ONE_MONTH || range == -THREE_MONTHS) { // 1 month or 6 month c.add(Calendar.MONTH, range); } String timeStart = String.valueOf(c.get(Calendar.YEAR)); timeStart += ("-" + String.valueOf(c.get(Calendar.MONTH) + 1)); timeStart += ("-" + String.valueOf(c.get(Calendar.DAY_OF_MONTH))); Calendar current = Calendar.getInstance(); current.add(Calendar.DAY_OF_MONTH, 1); String timeEnd = String.valueOf(current.get(Calendar.YEAR)); timeEnd += ("-" + String.valueOf(current.get(Calendar.MONTH) + 1)); timeEnd += ("-" + String.valueOf(current.get(Calendar.DAY_OF_MONTH))); JSONObject timeRange = new JSONObject(); timeRange.put("start", timeStart); timeRange.put("end", timeEnd); param.put("timeRange", timeRange); jsonstr.put("json", param); } else if (op == METHOD_TAG_SEARCH) { } else if (op == METHOD_KEY_DATE_SEARCH) { if (terms.length > 2) { // Add keys if there is any. JSONArray keys = new JSONArray(); int numTerm = terms.length - 2; for (int i = 0; i < numTerm; i++) { keys.put(terms[i]); } param.put("keys", keys); } else if (terms.length < 2) { System.out.println("Wrong terms: no start or end date."); return null; } JSONObject timeRange = new JSONObject(); timeRange.put("start", terms[terms.length - 2]); timeRange.put("end", terms[terms.length - 1]); param.put("timeRange", timeRange); jsonstr.put("json", param); } URL url = new URL(RECEIPT_OP_URL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // Must put "json=" here for server to decoding the data String data = "json=" + jsonstr.toString(); out.write(data); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); return in.readLine(); // String s = in.readLine(); // System.out.println(s); // return s; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:com.simiacryptus.util.Util.java
/** * Cache input stream.//from w w w . j ava 2 s . c o m * * @param url the url * @param file the file * @return the input stream * @throws IOException the io exception * @throws NoSuchAlgorithmException the no such algorithm exception * @throws KeyStoreException the key store exception * @throws KeyManagementException the key management exception */ public static InputStream cache(String url, String file) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { if (new File(file).exists()) { return new FileInputStream(file); } else { TrustManager[] trustManagers = { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, trustManagers, null); SSLSocketFactory sslFactory = ctx.getSocketFactory(); URLConnection urlConnection = new URL(url).openConnection(); if (urlConnection instanceof javax.net.ssl.HttpsURLConnection) { HttpsURLConnection conn = (HttpsURLConnection) urlConnection; conn.setSSLSocketFactory(sslFactory); conn.setRequestMethod("GET"); } InputStream inputStream = urlConnection.getInputStream(); FileOutputStream cache = new FileOutputStream(file); return new TeeInputStream(inputStream, cache); } }
From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java
public static String fetchSecureContent(final String url, final int timeout) throws IOException { LOGGER.info("fetchSecureContent: " + url); final URL u = new URL(url); final URLConnection conn = u.openConnection(); if (timeout != 0) { conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout);/*ww w . ja v a 2s . c o m*/ } if (conn instanceof HttpsURLConnection) { final HttpsURLConnection http = (HttpsURLConnection) conn; http.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); http.setRequestMethod(GET_STR); http.setAllowUserInteraction(true); } return IOUtils.toString(conn.getInputStream()); }
From source file:com.adrguides.utils.HTTPUtils.java
public static InputStream openAddress(Context context, URL url) throws IOException { if ("file".equals(url.getProtocol()) && url.getPath().startsWith("/android_asset/")) { return context.getAssets().open(url.getPath().substring(15)); // "/android_asset/".length() == 15 } else {// w ww . jav a2 s . co m URLConnection urlconn = url.openConnection(); urlconn.setReadTimeout(10000 /* milliseconds */); urlconn.setConnectTimeout(15000 /* milliseconds */); urlconn.setAllowUserInteraction(false); urlconn.setDoInput(true); urlconn.setDoOutput(false); if (urlconn instanceof HttpURLConnection) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responsecode = connection.getResponseCode(); if (responsecode != HttpURLConnection.HTTP_OK) { throw new IOException("Http response code returned:" + responsecode); } } return urlconn.getInputStream(); } }
From source file:edu.tum.cs.ias.knowrob.utils.ResourceRetriever.java
/** * Retrieve a file to a temporary path. This temporary path will be returned. Valid protocol * types: ftp, http, package or local file If a file has already be downloaded (the file is * existing in tmp directory) it will not be redownloaded again. Simply the path to this file * will be returned.// w w w . j a v a2 s . c o m * * @param url * URL to retrieve * @param checkAlreadyRetrieved * if false, always download the file and ignore, if it is already existing * @return NULL on error. On success the path to the file is returned. */ public static File retrieve(String url, boolean checkAlreadyRetrieved) { if (url.indexOf("://") <= 0) { // Is local file return new File(url); } int start = url.indexOf('/') + 2; int end = url.indexOf('/', start); String serverName = url.substring(start, end); if (url.startsWith("package://")) { String filePath = url.substring(end + 1); String pkgPath = findPackage(serverName); if (pkgPath == null) return null; return new File(pkgPath, filePath); } else if (url.startsWith("http://")) { OutputStream out = null; URLConnection conn = null; InputStream in = null; String filename = url.substring(url.lastIndexOf('/') + 1); File tmpPath = getTmpName(url, filename); if (checkAlreadyRetrieved && tmpPath.exists()) { return tmpPath; } try { // Get the URL URL urlClass = new URL(url); // Open an output stream to the destination file on our local filesystem out = new BufferedOutputStream(new FileOutputStream(tmpPath)); conn = urlClass.openConnection(); in = conn.getInputStream(); // Get the data byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); } // Done! Just clean up and get out } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { // Ignore if stream not possible to close } } return tmpPath; } else if (url.startsWith("ftp://")) { FTPClient client = new FTPClient(); OutputStream outStream = null; String filename = url.substring(url.lastIndexOf('/') + 1); File tmpPath = getTmpName(url, filename); if (checkAlreadyRetrieved && tmpPath.exists()) { System.out.println("Already retrieved: " + url + " to " + tmpPath.getAbsolutePath()); return tmpPath; } try { // Connect to the FTP server as anonymous client.connect(serverName); client.login("anonymous", "knowrob@example.com"); String remoteFile = url.substring(end); // Write the contents of the remote file to a FileOutputStream outStream = new FileOutputStream(tmpPath); client.retrieveFile(remoteFile, outStream); } catch (IOException ioe) { System.out.println("ResourceRetriever: Error communicating with FTP server: " + serverName + "\n" + ioe.getMessage()); } finally { try { outStream.close(); } catch (IOException e1) { // Ignore if stream not possible to close } try { client.disconnect(); } catch (IOException e) { System.out.println("ResourceRetriever: Problem disconnecting from FTP server: " + serverName + "\n" + e.getMessage()); } } return tmpPath; } return null; }
From source file:com.sim2dial.dialer.ChatFragment.java
public static Bitmap downloadImage(String stringUrl) { URL url;//from w w w.j a v a2 s . co m Bitmap bm = null; try { url = new URL(stringUrl); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } byte[] rawImage = baf.toByteArray(); bm = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length); bis.close(); } catch (Exception e) { e.printStackTrace(); } return bm; }
From source file:mas.MAS.java
/** * @param args the command line arguments *///from www.j a v a 2s .com // for old version public static void getData(int startIdx, int endIdx) { try { Properties prop = new Properties(); prop.setProperty("AppId", "1df63064-efad-4bbd-a797-1131499b7728"); prop.setProperty("ResultObjects", "publication"); prop.setProperty("DomainID", "22"); prop.setProperty("SubDomainID", "2"); prop.setProperty("YearStart", "2001"); prop.setProperty("YearEnd", "2010"); prop.setProperty("StartIdx", startIdx + ""); prop.setProperty("EndIdx", endIdx + ""); String url_org = "http://academic.research.microsoft.com/json.svc/search"; String url_str = generateURL(url_org, prop); URL url = new URL(url_str); URLConnection yc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (MalformedURLException ex) { Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.frostwire.gui.library.LibraryUtils.java
private static InternetRadioStation processInternetRadioStationUrl(String urlStr) throws Exception { URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.setConnectTimeout(10000);/*from w w w . ja va2 s. c o m*/ conn.setRequestProperty("User-Agent", "Java"); InputStream is = conn.getInputStream(); BufferedReader d = null; if (conn.getContentEncoding() != null) { d = new BufferedReader(new InputStreamReader(is, conn.getContentEncoding())); } else { d = new BufferedReader(new InputStreamReader(is)); } String pls = ""; String[] props = null; String strLine; int numLine = 0; while ((strLine = d.readLine()) != null) { pls += strLine + "\n"; if (strLine.startsWith("File1=")) { String streamUrl = strLine.split("=")[1]; props = processStreamUrl(streamUrl); } else if (strLine.startsWith("icy-name:")) { pls = ""; props = processStreamUrl(urlStr); break; } numLine++; if (numLine > 10) { if (props == null) { // not a valid pls break; } } } is.close(); if (props != null && props[0] != null) { return LibraryMediator.getLibrary().newInternetRadioStation(props[0], props[0], props[1], props[2], props[3], props[4], props[5], pls, false); } else { return null; } }