List of usage examples for java.net URL openConnection
public URLConnection openConnection() throws java.io.IOException
From source file:com.hack23.cia.service.external.common.impl.XmlAgentImpl.java
/** * Read input stream./*w w w . java2 s .c o m*/ * * @param accessUrl * the access url * @return the string * @throws Exception * the exception */ private static String readInputStream(final String accessUrl) throws Exception { final URL url = new URL(accessUrl.replace(" ", "")); final URLConnection connection = url.openConnection(); final InputStream stream = connection.getInputStream(); final BufferedReader inputStream = new BufferedReader(new InputStreamReader(stream)); return readWithStringBuffer(inputStream); }
From source file:com.wareninja.opensource.common.wsrequest.HttpUtils.java
/** * Open an URL connection. If HTTPS, accepts any certificate even if not * valid, and connects to any host name. * /*from ww w .j ava 2 s . c o m*/ * @param url * The destination URL, HTTP or HTTPS. * @return The URLConnection. * @throws IOException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static URLConnection getConnection(URL url) throws IOException, NoSuchAlgorithmException, KeyManagementException { URLConnection conn = url.openConnection(); if (conn instanceof HttpsURLConnection) { // Trust all certificates SSLContext context = SSLContext.getInstance("TLS"); context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom()); SSLSocketFactory socketFactory = context.getSocketFactory(); ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory); // Allow all hostnames ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER); } conn.setConnectTimeout(SOCKET_TIMEOUT); conn.setReadTimeout(SOCKET_TIMEOUT); return conn; }
From source file:at.illecker.sentistorm.commons.util.io.IOUtils.java
public static InputStream getInputStream(String fileOrUrl, boolean unzip) { InputStream in = null;//from w w w. j av a 2 s . co m try { if (fileOrUrl.matches("https?://.*")) { URL u = new URL(fileOrUrl); URLConnection uc = u.openConnection(); in = uc.getInputStream(); } else { // 1) check if file is within jar in = IOUtils.class.getClassLoader().getResourceAsStream(fileOrUrl); // windows File.separator is \, but getting resources only works with / if (in == null) { in = IOUtils.class.getClassLoader().getResourceAsStream(fileOrUrl.replaceAll("\\\\", "/")); } // 2) if not found in jar, load from the file system if (in == null) { in = new FileInputStream(fileOrUrl); } } // unzip if necessary if ((unzip) && (fileOrUrl.endsWith(".gz"))) { in = new GZIPInputStream(in, GZIP_FILE_BUFFER_SIZE); } // buffer input stream in = new BufferedInputStream(in); } catch (FileNotFoundException e) { LOG.error("FileNotFoundException: " + e.getMessage()); } catch (IOException e) { LOG.error("IOException: " + e.getMessage()); } return in; }
From source file:Main.java
public static String postMultiPart(String urlTo, String post, String filepath, String filefield) throws ParseException, IOException { HttpURLConnection connection = null; DataOutputStream outputStream = null; InputStream inputStream = null; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; String result = ""; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String[] q = filepath.split("/"); int idx = q.length - 1; try {/* w w w. ja v a 2 s. c o m*/ File file = new File(filepath); FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(urlTo); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd); outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); // Upload POST Data String[] posts = post.split("&"); int max = posts.length; for (int i = 0; i < max; i++) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); String[] kv = posts[i].split("="); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd); outputStream.writeBytes("Content-Type: text/plain" + lineEnd); outputStream.writeBytes(lineEnd); outputStream.writeBytes(kv[1]); outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); inputStream = connection.getInputStream(); result = convertStreamToString(inputStream); fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); return result; } catch (Exception e) { Log.e("MultipartRequest", "Multipart Form Upload Error"); e.printStackTrace(); return "error"; } }
From source file:com.sfxie.extension.spring4.properties.PropertiesLoaderUtils.java
/** * Load all properties from the specified class path resource * (in ISO-8859-1 encoding), using the given class loader. * <p>Merges properties if more than one resource of the same name * found in the class path.//w ww . j a va2s . c o m * @param resourceName the name of the class path resource * @param classLoader the ClassLoader to use for loading * (or {@code null} to use the default class loader) * @return the populated Properties instance * @throws IOException if loading failed */ public static Properties loadAllProperties(String resourceName, ClassLoader classLoader) throws IOException { Assert.notNull(resourceName, "Resource name must not be null"); ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = ClassUtils.getDefaultClassLoader(); } Enumeration<URL> urls = (classLoaderToUse != null ? classLoaderToUse.getResources(resourceName) : ClassLoader.getSystemResources(resourceName)); Properties props = new Properties(); while (urls.hasMoreElements()) { URL url = urls.nextElement(); URLConnection con = url.openConnection(); ResourceUtils.useCachesIfNecessary(con); InputStream is = con.getInputStream(); try { if (resourceName != null && resourceName.endsWith(XML_FILE_EXTENSION)) { props.loadFromXML(is); } else { props.load(is); } } finally { is.close(); } } return props; }
From source file:com.flexdesktop.connections.restfulConnection.java
public static String postRESTful(String RESTfull_URL, String data) { String state = ""; try {/*from w ww . j a va2s .com*/ URL url = new URL(RESTfull_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request postRequest(connection, data); //Get Response state = postResponse(connection); if (connection != null) { connection.disconnect(); } } catch (Exception ex) { Logger.getLogger(com.flexdesktop.connections.restfulConnection.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(state); return state; }
From source file:itdelatrisu.opsu.downloads.BloodcatServer.java
/** * Returns a JSON object from a URL./*from www.ja v a 2s .c o m*/ * @param url the remote URL * @return the JSON object * @author Roland Illig (http://stackoverflow.com/a/4308662) */ public static JSONObject readJsonFromUrl(URL url) throws IOException { // open connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(Download.CONNECTION_TIMEOUT); conn.setReadTimeout(Download.READ_TIMEOUT); conn.setUseCaches(false); try { conn.connect(); } catch (SocketTimeoutException e) { ErrorHandler.error("Connection to server timed out.", e, false); throw e; } if (Thread.interrupted()) return null; // read JSON JSONObject json = null; try (InputStream in = conn.getInputStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); int c; while ((c = rd.read()) != -1) sb.append((char) c); json = new JSONObject(sb.toString()); } catch (SocketTimeoutException e) { ErrorHandler.error("Connection to server timed out.", e, false); throw e; } catch (JSONException e1) { ErrorHandler.error("Failed to create JSON object.", e1, true); } return json; }
From source file:Main.java
public static InputStream getImageStreamFromUrl(String stringUrl) { URL url; try {/*w w w .j av a 2 s.c o m*/ url = new URL(stringUrl); } catch (MalformedURLException e1) { throw new RuntimeException(e1); } InputStream input = null; try { input = url.openConnection().getInputStream(); } catch (IOException e) { throw new RuntimeException(e); } return input; }
From source file:Main.java
public static void DownloadFromUrl(String thisUrl, String path, String filename) { Log.d("DownloadFromUrl", "url: " + thisUrl); Log.d("DownloadFromUrl", "path: " + path); Log.d("DownloadFromUrl", "filename: " + filename); try {/*from www .j a va 2s.c o m*/ URL url = new URL(thisUrl); new File(path).mkdirs(); File file = new File(path, filename); /* Open a connection to that URL. */ URLConnection ucon = url.openConnection(); Log.d("DownloadFromUrl", "about to write file"); /* * Define InputStreams to read from the URLConnection. */ InputStream is = ucon.getInputStream(); try { OutputStream os = new FileOutputStream(file); try { byte[] buffer = new byte[4096]; for (int n; (n = is.read(buffer)) != -1;) os.write(buffer, 0, n); } finally { os.close(); } } finally { is.close(); } Log.d("DownloadFromUrl", "finished"); } catch (IOException e) { Log.d("DownloadFromUrl", "Error: " + e); } }
From source file:Main.java
public static Reader getUri(URL url) throws IOException { //Log.d(TAG, "getUri: " + url.toString()); boolean useGzip = false; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(30 * 1000);//from w w w. j a va 2 s . c o m conn.setRequestProperty("Accept-Encoding", "gzip"); conn.connect(); InputStream in = conn.getInputStream(); final Map<String, List<String>> headers = conn.getHeaderFields(); // This is a map, but we can't assume the key we're looking for // is in normal casing. So it's really not a good map, is it? final Set<Map.Entry<String, List<String>>> set = headers.entrySet(); for (Iterator<Map.Entry<String, List<String>>> i = set.iterator(); i.hasNext();) { Map.Entry<String, List<String>> entry = i.next(); if ("Content-Encoding".equalsIgnoreCase(entry.getKey())) { for (Iterator<String> j = entry.getValue().iterator(); j.hasNext();) { String str = j.next(); if (str.equalsIgnoreCase("gzip")) { useGzip = true; break; } } // Break out of outer loop. if (useGzip) { break; } } } if (useGzip) { return new BufferedReader(new InputStreamReader(new GZIPInputStream(in)), 8 * 1024); } else { return new BufferedReader(new InputStreamReader(in), 8 * 1024); } }