Java Code Examples for java.net.URLConnection

The following examples show how to use java.net.URLConnection. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: helidon-build-tools   Source File: NetworkConnection.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 2
Source Project: FamilyChat   Source File: OkPostFormRequest.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: groovy   Source File: GroovyScriptEngine.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: smallrye-config   Source File: InjectionTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: qpid-broker-j   Source File: Handler.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
/**
 * 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 7
Source Project: ns4_frame   Source File: PerformanceTester.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: jdk8u-dev-jdk   Source File: B7050028.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 9
Source Project: SpringBootUnity   Source File: DownUtil.java    License: MIT License 6 votes vote down vote up
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 10
Source Project: jgroups-kubernetes   Source File: TokenStreamProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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 11
Source Project: djl   Source File: DownloadUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 12
Source Project: PDFCreatorAndroid   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@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 13
Source Project: openjdk-8-source   Source File: B7050028.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 Project: commons-vfs   Source File: AbstractProviderTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: UhcCore   Source File: MojangUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
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
/**
 * 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.
 * @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;
}
 
Example 17
Source Project: hadoop   Source File: ClusterJspHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Read in the content from a URL
 * @param url URL To read
 * @return the text from the output
 * @throws IOException if something went wrong
 */
private static String readOutput(URL url) throws IOException {
  StringBuilder out = new StringBuilder();
  URLConnection connection = url.openConnection();
  BufferedReader in = new BufferedReader(
                          new InputStreamReader(
                          connection.getInputStream(), Charsets.UTF_8));
  String inputLine;
  while ((inputLine = in.readLine()) != null) {
    out.append(inputLine);
  }
  in.close();
  return out.toString();
}
 
Example 18
Source Project: tomee   Source File: OpenEJBContextConfig.java    License: Apache License 2.0 5 votes vote down vote up
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 19
public URLValidator(URI uri, URLConnection urlConnection,
        long request_time, UrlConnectionExpiryCalculator
        urlConnectionExpiryCalculator) {
    this.uri = uri;
    this.lastModified = urlConnection.getLastModified();
    this.entityTags = getEntityTags(urlConnection);
    expiry = calculateExpiry(urlConnection, request_time,
            urlConnectionExpiryCalculator);
}
 
Example 20
Source Project: android-apps   Source File: HttpHelper.java    License: MIT License 5 votes vote down vote up
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 21
Source Project: Tomcat8-Source-Read   Source File: JreCompat.java    License: MIT License 5 votes vote down vote up
/**
 * Disables caching for JAR URL connections. For Java 8 and earlier, this also disables
 * caching for ALL URL connections.
 *
 * @throws IOException If a dummy JAR URLConnection can not be created
 */
public void disableCachingForJarUrlConnections() throws IOException {
    // Doesn't matter that this JAR doesn't exist - just as
    // long as the URL is well-formed
    URL url = new URL("jar:file://dummy.jar!/");
    URLConnection uConn = url.openConnection();
    uConn.setDefaultUseCaches(false);
}
 
Example 22
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 23
Source Project: Tomcat8-Source-Read   Source File: TestWarURLConnection.java    License: MIT License 5 votes vote down vote up
@Test
public void testContentLength() throws Exception {
    File f = new File("test/webresources/war-url-connection.war");
    String fileUrl = f.toURI().toURL().toString();

    URL indexHtmlUrl = new URL("jar:war:" + fileUrl +
            "*/WEB-INF/lib/test.jar!/META-INF/resources/index.html");

    URLConnection urlConn = indexHtmlUrl.openConnection();
    urlConn.connect();

    int size = urlConn.getContentLength();

    Assert.assertEquals(137, size);
}
 
Example 24
Source Project: reacteu-app   Source File: FileTransfer.java    License: MIT License 5 votes vote down vote up
private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {
    String encoding = conn.getContentEncoding();
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
      return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));
    }
    return new SimpleTrackingInputStream(conn.getInputStream());
}
 
Example 25
private AddDeploymentPlanBuilder add(String name, String commonName, URL url) throws IOException, DuplicateDeploymentNameException {
    URLConnection conn = url.openConnection();
    conn.connect();
    InputStream stream = conn.getInputStream();
    try {
        return add(name, commonName, stream);
    }
    finally {
        try { stream.close(); } catch (Exception ignored) {}
    }
}
 
Example 26
Source Project: egdownloader   Source File: Proxy.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static String getHtml(String address){  
    StringBuffer html = new StringBuffer();  
    String result = null;  
    try{  
        URL url = new URL(address);  
        URLConnection conn = url.openConnection();  
        conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; NT 5.1; GTB5; .NET CLR 2.0.50727; CIBA)");  
        BufferedInputStream in = new BufferedInputStream(conn.getInputStream());  
          
        try{  
            String inputLine;  
            byte[] buf = new byte[4096];  
            int bytesRead = 0;  
            while (bytesRead >= 0) {  
                inputLine = new String(buf, 0, bytesRead, "ISO-8859-1");  
                html.append(inputLine);  
                bytesRead = in.read(buf);  
                inputLine = null;  
            }  
            buf = null;  
        }finally{  
            in.close();  
            conn = null;  
            url = null;  
        }  
        result = new String(html.toString().trim().getBytes("ISO-8859-1"), "gb2312").toLowerCase();  
          
    }catch (Exception e) {  
        e.printStackTrace();  
        return null;  
    }finally{  
        html = null;              
    }  
    return result;  
}
 
Example 27
Source Project: openjdk-jdk9   Source File: JarFileFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
URLConnection getConnection(JarFile jarFile) throws IOException {
    URL u;
    synchronized (instance) {
        u = urlCache.get(jarFile);
    }
    if (u != null)
        return u.openConnection();

    return null;
}
 
Example 28
private static String readBuildDateFromManifest() {
	try {
		final URLConnection jarConnection = getLocationOfClass().openConnection();
		if ( !(jarConnection instanceof JarURLConnection) ) {
			return null;
		}
		final JarURLConnection conn = (JarURLConnection) jarConnection;
		final Manifest mf = conn.getManifest();
		final Attributes atts = mf.getMainAttributes();
		return atts.getValue( "Build-Time" );
	} catch ( final IOException e ) {
		return null;
	}
}
 
Example 29
Source Project: Wurst7   Source File: GoogleTranslate.java    License: GNU General Public License v3.0 5 votes vote down vote up
private URLConnection setupConnection(URL url) throws IOException
{
	URLConnection connection = url.openConnection();
	
	connection.setConnectTimeout(5000);
	connection.setRequestProperty("User-Agent",
		"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
	
	return connection;
}
 
Example 30
Source Project: jcifs   Source File: Handler.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public URLConnection openConnection ( URL u ) throws IOException {
    if ( log.isDebugEnabled() ) {
        log.debug("Opening file " + u);
    }
    return new SmbFile(u, getTransportContext());
}