java.net.URLConnection Java Examples
The following examples show how to use
java.net.URLConnection.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MainActivity.java From PDFCreatorAndroid with MIT License | 7 votes |
@Override protected void onNextClicked(File savedPDFFile) { Intent intentShareFile = new Intent(Intent.ACTION_SEND); Uri apkURI = FileProvider.getUriForFile( getApplicationContext(), getApplicationContext() .getPackageName() + ".provider", savedPDFFile); intentShareFile.setDataAndType(apkURI, URLConnection.guessContentTypeFromName(savedPDFFile.getName())); intentShareFile.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intentShareFile.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + savedPDFFile.getAbsolutePath())); startActivity(Intent.createChooser(intentShareFile, "Share File")); }
Example #2
Source File: Handler.java From qpid-broker-j with Apache License 2.0 | 6 votes |
@Override protected URLConnection openConnection(final URL u) throws IOException { String externalForm = u.toExternalForm(); if(externalForm.startsWith("classpath:")) { String path = externalForm.substring(10); URL resourceUrl = getClass().getClassLoader().getResource(path); if(resourceUrl == null) { throw new FileNotFoundException("No such resource found in the classpath: " + path); } return resourceUrl.openConnection(); } else { throw new MalformedURLException("'"+externalForm+"' does not start with 'classpath:'"); } }
Example #3
Source File: GroovyScriptEngine.java From groovy with Apache License 2.0 | 6 votes |
/** * Get the class of the scriptName in question, so that you can instantiate * Groovy objects with caching and reloading. * * @param scriptName resource name pointing to the script * @return the loaded scriptName as a compiled class * @throws ResourceException if there is a problem accessing the script * @throws ScriptException if there is a problem parsing the script */ public Class loadScriptByName(String scriptName) throws ResourceException, ScriptException { URLConnection conn = rc.getResourceConnection(scriptName); String path = conn.getURL().toExternalForm(); ScriptCacheEntry entry = scriptCache.get(path); Class clazz = null; if (entry != null) clazz = entry.scriptClass; try { if (isSourceNewer(entry)) { try { String encoding = conn.getContentEncoding() != null ? conn.getContentEncoding() : config.getSourceEncoding(); String content = IOGroovyMethods.getText(conn.getInputStream(), encoding); clazz = groovyLoader.parseClass(content, path); } catch (IOException e) { throw new ResourceException(e); } } } finally { forceClose(conn); } return clazz; }
Example #4
Source File: NetworkConnection.java From helidon-build-tools with Apache License 2.0 | 6 votes |
/** * Connect, retrying if needed. * * @return The connection. */ public URLConnection connect() throws IOException { if (url == null) { throw new IllegalStateException("url is required"); } Log.debug("connecting to %s, headers=%s", url, headers); IOException lastCaught = null; for (int attempt = 1; attempt <= maxAttempts; attempt++) { try { URLConnection result = connector.connect(url, headers, connectTimeout, readTimeout); Log.debug("connected to %s, headers=%s", url, result.getHeaderFields()); return result; } catch (UnknownHostException | SocketException | SocketTimeoutException e) { lastCaught = e; delay.execute(attempt, maxAttempts); } } throw requireNonNull(lastCaught); }
Example #5
Source File: OkPostFormRequest.java From FamilyChat with Apache License 2.0 | 6 votes |
private String guessMimeType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = null; try { contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (contentTypeFor == null) { contentTypeFor = "application/octet-stream"; } return contentTypeFor; }
Example #6
Source File: InjectionTest.java From smallrye-config with Apache License 2.0 | 6 votes |
@Override protected URLConnection openConnection(final URL u) throws IOException { if (!u.getFile().endsWith("SmallRyeConfigFactory")) { return null; } return new URLConnection(u) { @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(contents); } }; }
Example #7
Source File: PlacesService.java From MuslimMateAndroid with GNU General Public License v3.0 | 6 votes |
/** * Function to send request to google places api * * @param theUrl Request url * @return Json response */ private String getUrlContents(String theUrl) { StringBuilder content = new StringBuilder(); try { URL url = new URL(theUrl); URLConnection urlConnection = url.openConnection(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(urlConnection.getInputStream()), 8); String line; while ((line = bufferedReader.readLine()) != null) { content.append(line + "\n"); } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } return content.toString(); }
Example #8
Source File: PerformanceTester.java From ns4_frame with Apache License 2.0 | 6 votes |
@Override public void run() { //访问特定的dispatcher地址 long startTime = System.currentTimeMillis(); try { URL url = new URL(targetUrl); URLConnection httpURLConnection = url.openConnection(); httpURLConnection.setUseCaches(false); httpURLConnection.connect(); Object o = httpURLConnection.getContent(); long cost = (System.currentTimeMillis()-startTime); if (cost > 100) { logger.debug(o + " cost:"+cost+"ms"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
Example #9
Source File: B7050028.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection(); int len = conn.getContentLength(); byte[] data = new byte[len]; InputStream is = conn.getInputStream(); is.read(data); is.close(); conn.setDefaultUseCaches(false); File jar = File.createTempFile("B7050028", ".jar"); jar.deleteOnExit(); OutputStream os = new FileOutputStream(jar); ZipOutputStream zos = new ZipOutputStream(os); ZipEntry ze = new ZipEntry("B7050028.class"); ze.setMethod(ZipEntry.STORED); ze.setSize(len); CRC32 crc = new CRC32(); crc.update(data); ze.setCrc(crc.getValue()); zos.putNextEntry(ze); zos.write(data, 0, len); zos.closeEntry(); zos.finish(); zos.close(); os.close(); System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName())); }
Example #10
Source File: DownUtil.java From SpringBootUnity with MIT License | 6 votes |
public static void download(String urlString) throws Exception { File file = new File(urlString); String filename = file.getName(); // 构造URL URL url = new URL(urlString); // 打开连接 URLConnection con = url.openConnection(); // 输入流 InputStream is = con.getInputStream(); // 1K的数据缓冲 byte[] bs = new byte[1024]; // 读取到的数据长度 int len; // 输出的文件流 OutputStream os = new FileOutputStream(filename); // 开始读取 while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } // 完毕,关闭所有链接 os.close(); is.close(); }
Example #11
Source File: TokenStreamProvider.java From jgroups-kubernetes with Apache License 2.0 | 6 votes |
@Override public InputStream openStream(String url, Map<String, String> headers, int connectTimeout, int readTimeout) throws IOException { URLConnection connection = openConnection(url, headers, connectTimeout, readTimeout); if (connection instanceof HttpsURLConnection) { HttpsURLConnection httpsConnection = HttpsURLConnection.class.cast(connection); //httpsConnection.setHostnameVerifier(InsecureStreamProvider.INSECURE_HOSTNAME_VERIFIER); httpsConnection.setSSLSocketFactory(getSSLSocketFactory()); if (log.isLoggable(Level.FINE)) { log.fine(String.format("Using HttpsURLConnection with SSLSocketFactory [%s] for url [%s].", factory, url)); } } else { if (log.isLoggable(Level.FINE)) { log.fine(String.format("Using URLConnection for url [%s].", url)); } } if (token != null) { // curl -k -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" \ // https://172.30.0.2:443/api/v1/namespaces/dward/pods?labelSelector=application%3Deap-app headers.put("Authorization", "Bearer " + token); } return connection.getInputStream(); }
Example #12
Source File: DownloadUtils.java From djl with Apache License 2.0 | 6 votes |
/** * Downloads a file from specified url. * * @param url the url to download * @param output the output location * @param progress the progress tracker to show download progress * @throws IOException when IO operation fails in downloading */ public static void download(URL url, Path output, Progress progress) throws IOException { if (Files.exists(output)) { return; } Path dir = output.toAbsolutePath().getParent(); if (dir != null) { Files.createDirectories(dir); } URLConnection conn = url.openConnection(); if (progress != null) { long contentLength = conn.getContentLengthLong(); if (contentLength > 0) { progress.reset("Downloading", contentLength, output.toFile().getName()); } } try (InputStream is = conn.getInputStream()) { ProgressInputStream pis = new ProgressInputStream(is, progress); String fileName = url.getFile(); if (fileName.endsWith(".gz")) { Files.copy(new GZIPInputStream(pis), output); } else { Files.copy(pis, output); } } }
Example #13
Source File: B7050028.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection(); int len = conn.getContentLength(); byte[] data = new byte[len]; InputStream is = conn.getInputStream(); is.read(data); is.close(); conn.setDefaultUseCaches(false); File jar = File.createTempFile("B7050028", ".jar"); jar.deleteOnExit(); OutputStream os = new FileOutputStream(jar); ZipOutputStream zos = new ZipOutputStream(os); ZipEntry ze = new ZipEntry("B7050028.class"); ze.setMethod(ZipEntry.STORED); ze.setSize(len); CRC32 crc = new CRC32(); crc.update(data); ze.setCrc(crc.getValue()); zos.putNextEntry(ze); zos.write(data, 0, len); zos.closeEntry(); zos.finish(); zos.close(); os.close(); System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName())); }
Example #14
Source File: AbstractProviderTestCase.java From commons-vfs with Apache License 2.0 | 6 votes |
/** * Asserts that the content of a file is the same as expected. Checks the length reported by getContentLength() is * correct, then reads the content as a byte stream and compares the result with the expected content. Assumes files * are encoded using UTF-8. */ protected void assertSameURLContent(final String expected, final URLConnection connection) throws Exception { // Get file content as a binary stream final byte[] expectedBin = expected.getBytes("utf-8"); // Check lengths assertEquals("same content length", expectedBin.length, connection.getContentLength()); // Read content into byte array final InputStream instr = connection.getInputStream(); final ByteArrayOutputStream outstr; try { outstr = new ByteArrayOutputStream(); final byte[] buffer = new byte[256]; int nread = 0; while (nread >= 0) { outstr.write(buffer, 0, nread); nread = instr.read(buffer); } } finally { instr.close(); } // Compare assertArrayEquals("same binary content", expectedBin, outstr.toByteArray()); }
Example #15
Source File: MojangUtils.java From UhcCore with GNU General Public License v3.0 | 6 votes |
public static String getPlayerName(UUID uuid){ if (Bukkit.isPrimaryThread()){ throw new RuntimeException("Requesting player UUID is not allowed on the primary thread!"); } try { URL url = new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names"); URLConnection request = url.openConnection(); request.connect(); JsonParser jp = new JsonParser(); JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); JsonArray names = root.getAsJsonArray(); return names.get(names.size()-1).getAsJsonObject().get("name").getAsString(); }catch (IOException ex){ ex.printStackTrace(); return null; } }
Example #16
Source File: OpenEJBContextConfig.java From tomee with Apache License 2.0 | 5 votes |
private URL replaceKnownRealmsByTomEEOnes(final URL contextXml) throws MalformedURLException { return new URL(contextXml.getProtocol(), contextXml.getHost(), contextXml.getPort(), contextXml.getFile(), new URLStreamHandler() { @Override protected URLConnection openConnection(final URL u) throws IOException { final URLConnection c = contextXml.openConnection(); return new URLConnection(u) { @Override public void connect() throws IOException { c.connect(); } @Override public InputStream getInputStream() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IO.copy(c.getInputStream(), baos); return new ByteArrayInputStream(new String(baos.toByteArray()) .replace(DataSourceRealm.class.getName(), TomEEDataSourceRealm.class.getName() ).getBytes()); } @Override public String toString() { return c.toString(); } }; } }); }
Example #17
Source File: FileResourceUtil.java From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License | 5 votes |
static File renameFile(File file, String newFileName, Context context) { String contentType = URLConnection.guessContentTypeFromName(file.getName()); String generatedName = generateFileName(MediaType.get(contentType), newFileName); File newFile = new File(context.getFilesDir(), "sdk_resources/" + generatedName); if (!file.renameTo(newFile)) { Log.d(FileResourceUtil.class.getCanonicalName(), "Fail renaming " + file.getName() + " to " + generatedName); } return newFile; }
Example #18
Source File: LoadDataServletRun.java From rya with Apache License 2.0 | 5 votes |
public static void main(String[] args) { try { final InputStream resourceAsStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("namedgraphs.trig"); URL url = new URL("http://localhost:8080/web.rya/loadrdf" + "?format=Trig" + "&cv=ROSH|ANDR"); URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Content-Type", "text/plain"); urlConnection.setDoOutput(true); final OutputStream os = urlConnection.getOutputStream(); int read; while((read = resourceAsStream.read()) >= 0) { os.write(read); } resourceAsStream.close(); os.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader( urlConnection.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } }
Example #19
Source File: URLClassPath.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
static void check(URL url) throws IOException { SecurityManager security = System.getSecurityManager(); if (security != null) { URLConnection urlConnection = url.openConnection(); Permission perm = urlConnection.getPermission(); if (perm != null) { try { security.checkPermission(perm); } catch (SecurityException se) { // fallback to checkRead/checkConnect for pre 1.2 // security managers if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) { security.checkRead(perm.getName()); } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) { URL locUrl = url; if (urlConnection instanceof JarURLConnection) { locUrl = ((JarURLConnection)urlConnection).getJarFileURL(); } security.checkConnect(locUrl.getHost(), locUrl.getPort()); } else { throw se; } } } } }
Example #20
Source File: JarFileFactory.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
URLConnection getConnection(JarFile jarFile) throws IOException { URL u; synchronized (instance) { u = urlCache.get(jarFile); } if (u != null) return u.openConnection(); return null; }
Example #21
Source File: HttpClientUtil.java From charging_pile_cloud with MIT License | 5 votes |
/** * 封装HTTP GET方法 * * @param * @return * @throws Exception */ public static String get(String url) throws Exception { URL u = new URL(url); if("https".equalsIgnoreCase(u.getProtocol())){ SSLUtil.ignoreSsl(); } URLConnection conn = u.openConnection(); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); return IOUtils.toString(conn.getInputStream()); }
Example #22
Source File: HttpHelper.java From android-apps with MIT License | 5 votes |
private static String consume(URLConnection connection) throws IOException { String encoding = getEncoding(connection); ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = connection.getInputStream(); try { in = connection.getInputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } } finally { try { in.close(); } catch (IOException ioe) { // continue } } try { return new String(out.toByteArray(), encoding); } catch (UnsupportedEncodingException uee) { try { return new String(out.toByteArray(), "UTF-8"); } catch (UnsupportedEncodingException uee2) { // can't happen throw new IllegalStateException(uee2); } } }
Example #23
Source File: HtmlDocumentation.java From netbeans with Apache License 2.0 | 5 votes |
static String getContentAsString(URL url, Charset charset) { String filePath = url.getPath(); String cachedContent = HELP_FILES_CACHE.get(filePath); if(cachedContent != null) { return cachedContent; } if (charset == null) { charset = Charset.defaultCharset(); } try { URLConnection con = url.openConnection(); con.connect(); Reader r = new InputStreamReader(new BufferedInputStream(con.getInputStream()), charset); char[] buf = new char[2048]; int read; StringBuilder content = new StringBuilder(); while ((read = r.read(buf)) != -1) { content.append(buf, 0, read); } r.close(); String strContent = content.toString(); HELP_FILES_CACHE.put(filePath, strContent); return strContent; } catch (IOException ex) { Logger.getLogger(HtmlDocumentation.class.getName()).log(Level.SEVERE, null, ex); } return null; }
Example #24
Source File: BinaryIn.java From java_jail with GNU Affero General Public License v3.0 | 5 votes |
/** * Create a binary input stream from a URL. */ public BinaryIn(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); in = new BufferedInputStream(is); fillBuffer(); } catch (IOException ioe) { System.err.println("Could not open " + url); } }
Example #25
Source File: MetaHandler.java From fabric-installer with Apache License 2.0 | 5 votes |
public void load() throws IOException { URL url = new URL(metaUrl); URLConnection conn = url.openConnection(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { String json = reader.lines().collect(Collectors.joining("\n")); Type type = new TypeToken<ArrayList<GameVersion>>() {}.getType(); versions = Utils.GSON.fromJson(json, type); complete(versions); } }
Example #26
Source File: AndroidProtocolHandler.java From android-chromium with BSD 2-Clause "Simplified" License | 5 votes |
/** * Determine the mime type for an Android resource. * @param context The context manager. * @param stream The opened input stream which to examine. * @param url The url from which the stream was opened. * @return The mime type or null if the type is unknown. */ // TODO(bulach): this should have either a throw clause, or // handle the exception in the java side rather than the native side. @CalledByNativeUnchecked public static String getMimeType(Context context, InputStream stream, String url) { Uri uri = verifyUrl(url); if (uri == null) { return null; } String path = uri.getPath(); // The content URL type can be queried directly. if (uri.getScheme().equals(CONTENT_SCHEME)) { return context.getContentResolver().getType(uri); // Asset files may have a known extension. } else if (uri.getScheme().equals(FILE_SCHEME) && path.startsWith(nativeGetAndroidAssetPath())) { String mimeType = URLConnection.guessContentTypeFromName(path); if (mimeType != null) { return mimeType; } } // Fall back to sniffing the type from the stream. try { return URLConnection.guessContentTypeFromStream(stream); } catch (IOException e) { return null; } }
Example #27
Source File: ImageLoadUtil.java From mobile-manager-tool with MIT License | 5 votes |
/** * 尝试获取图片资源 * * @param url * @return */ private static boolean connectImageUrl(String url) { try { URL imageUrl = new URL(url);// 创建URL对象。 URLConnection uc = imageUrl.openConnection();// 创建一个连接对象。 InputStream in = uc.getInputStream();// 获取连接对象输入字节流。如果地址无效则会抛出异常。 in.close(); return true; } catch (Exception e) { Log.e("connectImageUrl", "图片资源" + url + "不存在"); return false; } }
Example #28
Source File: MimeTypesUtils.java From yes-cart with Apache License 2.0 | 5 votes |
/** * Detect MIME type from file name. * * @param fileName file name * * @return MIME type */ public static String getMimeType(String fileName) { final FileNameMap mimeTypes = URLConnection.getFileNameMap(); final String contentType = mimeTypes.getContentTypeFor(fileName); // nothing found -> look up our in extension map to find manually mapped types if (contentType == null) { final String extension = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length()); return EXT_MIMETYPE_MAP.get(extension); } return contentType; }
Example #29
Source File: PostFormRequest.java From VideoOS-Android-SDK with GNU General Public License v3.0 | 5 votes |
public static String guessMimeType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = null; try { contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (contentTypeFor == null) { contentTypeFor = "application/octet-stream"; } return contentTypeFor; }
Example #30
Source File: SSLContextInstrumentationTest.java From apm-agent-java with Apache License 2.0 | 5 votes |
private void createConnection() { try { URLConnection urlConnection = new URL("https://localhost:11111").openConnection(); assertThat(urlConnection).isInstanceOf(HttpsURLConnection.class); } catch (IOException e) { throw new RuntimeException(e); } }