Java Code Examples for java.net.URLConnection#connect()

The following examples show how to use java.net.URLConnection#connect() . 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: TrackerLoadTester.java    From TorrentEngine with GNU General Public License v3.0 6 votes vote down vote up
private void announce(String trackerURL,byte[] hash,byte[] peerId,int port) {
  try {
    String strUrl = trackerURL 
    	+ "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20")
    	+ "&peer_id="   + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20")
    	+ "&port=" + port
    	+ "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1";
    //System.out.println(strUrl);
    URL url = new URL(strUrl);
    URLConnection con = url.openConnection();
    con.connect();
    con.getContent();
  } catch(Exception e) {
    e.printStackTrace();
  }    
}
 
Example 2
Source File: Utility.java    From FacebookNewsfeedSample-Android with Apache License 2.0 6 votes vote down vote up
public static Bitmap getBitmap(String url) {
    Bitmap bm = null;
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
        bis.close();
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
    return bm;
}
 
Example 3
Source File: DeploymentPlanBuilderImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 4
Source File: VideoContentSearch.java    From Beedio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    numLinksInspected++;
    onStartInspectingURL();
    Log.i(TAG, "retreiving headers from " + url);

    URLConnection uCon = null;
    try {
        uCon = new URL(url).openConnection();
        uCon.connect();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (uCon != null) {
        String contentType = uCon.getHeaderField("content-type");

        if (contentType != null) {
            contentType = contentType.toLowerCase();
            if (contentType.contains("video") || contentType.contains
                    ("audio")) {
                addVideoToList(uCon, page, title, contentType);
            } else if (contentType.equals("application/x-mpegurl") ||
                    contentType.equals("application/vnd.apple.mpegurl")) {
                addVideosToListFromM3U8(uCon, page, title, contentType);
            } else Log.i(TAG, "Not a video. Content type = " +
                    contentType);
        } else {
            Log.i(TAG, "no content type");
        }
    } else Log.i(TAG, "no connection");

    numLinksInspected--;
    boolean finishedAll = false;
    if (numLinksInspected <= 0) {
        finishedAll = true;
    }
    onFinishedInspectingURL(finishedAll);
}
 
Example 5
Source File: StandardContentProvider.java    From workspacemechanic with Eclipse Public License 1.0 5 votes vote down vote up
public long lastModifiedTime(URI uri) throws IOException {
  URLConnection connection = uri.toURL().openConnection();

  // Using HEAD for Http connections.
  if (connection instanceof HttpURLConnection) {
    ((HttpURLConnection) connection).setRequestMethod("HEAD");
  }

  connection.connect();
  return connection.getLastModified();
}
 
Example 6
Source File: GluonServerCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns availability of Gluon server.
 *
 * @return isServerAvailable
 */
public boolean isEtcdSeverAvailable() {
    String serverUrl = GLUON_HTTP + ipAddress + ":" + port;
    boolean isServerAvailable;
    try {
        URL url = new URL(serverUrl);
        URLConnection connection = url.openConnection();
        connection.connect();
        isServerAvailable = true;
    } catch (IOException e) {
        print(NO_SERVER_AVAIL_ON_PORT);
        isServerAvailable = false;
    }
    return isServerAvailable;
}
 
Example 7
Source File: Viewer.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fetches the class file of the specified class from the http
 * server.
 */
protected byte[] fetchClass(String classname) throws Exception
{
    byte[] b;
    URL url = new URL("http", server, port,
                      "/" + classname.replace('.', '/') + ".class");
    URLConnection con = url.openConnection();
    con.connect();
    int size = con.getContentLength();
    InputStream s = con.getInputStream();
    if (size <= 0)
        b = readStream(s);
    else {
        b = new byte[size];
        int len = 0;
        do {
            int n = s.read(b, len, size - len);
            if (n < 0) {
                s.close();
                throw new IOException("the stream was closed: "
                                      + classname);
            }
            len += n;
        } while (len < size);
    }

    s.close();
    return b;
}
 
Example 8
Source File: ShopwareInstallerUtil.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
@Nullable
public static String getDownloadVersions() {

    String userAgent = String.format("%s / %s / Shopware Plugin %s",
        ApplicationInfo.getInstance().getVersionName(),
        ApplicationInfo.getInstance().getBuild(),
        PluginManager.getPlugin(PluginId.getId("de.espend.idea.shopware")).getVersion()
    );

    try {

        // @TODO: PhpStorm9:
        // simple replacement for: com.intellij.util.io.HttpRequests
        URL url = new URL("http://update-api.shopware.com/v1/releases/install?major=6");
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("User-Agent", userAgent);
        conn.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        StringBuilder content = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            content.append(line);
        }

        in.close();

        return content.toString();
    } catch (IOException e) {
        return null;
    }

}
 
Example 9
Source File: SensUtils.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 访问路径获取json数据
 *
 * @param enterUrl 路径
 * @return String
 */
public static String getHttpResponse(String enterUrl) {
    BufferedReader in = null;
    StringBuffer result = null;
    try {
        URI uri = new URI(enterUrl);
        URL url = uri.toURL();
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Charset", "utf-8");
        connection.connect();
        result = new StringBuffer();
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        return result.toString();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
    return null;
}
 
Example 10
Source File: MicroIntegratorRegistry.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Function to retrieve resource content as text
 *
 * @param url
 * @return
 * @throws IOException
 */
private OMNode readNonXML (URL url) throws IOException {

    URLConnection urlConnection = url.openConnection();
    urlConnection.connect();

    try (InputStream inputStream = urlConnection.getInputStream()) {

        if (inputStream == null) {
            return null;
        }

        String mediaType = DEFAULT_MEDIA_TYPE;
        Properties metadata = getMetadata(url.getPath());
        if (metadata != null) {
            mediaType = metadata.getProperty(METADATA_KEY_MEDIA_TYPE, DEFAULT_MEDIA_TYPE);
        }

        if (DEFAULT_MEDIA_TYPE.equals(mediaType)) {
            StringBuilder strBuilder = new StringBuilder();
            try (BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = bReader.readLine()) != null) {
                    strBuilder.append(line);
                }
            }
            return OMAbstractFactory.getOMFactory().createOMText(strBuilder.toString());
        } else {
            return OMAbstractFactory.getOMFactory()
                    .createOMText(new DataHandler(new SynapseBinaryDataSource(inputStream, mediaType)), true);
        }
    }
}
 
Example 11
Source File: UTR30DataFileGenerator.java    From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressForbidden(reason = "fetching resources from ICU repository is trusted")
private static URLConnection openConnection(URL url) throws IOException {
    final URLConnection connection = url.openConnection();
    connection.setUseCaches(false);
    connection.addRequestProperty("Cache-Control", "no-cache");
    connection.connect();
    return connection;
}
 
Example 12
Source File: TestWarURLConnection.java    From Tomcat8-Source-Read with 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 13
Source File: MavenDownloader.java    From NBANDROID-V2 with Apache License 2.0 4 votes vote down vote up
public static void downloadFully(URL url, File target) throws IOException {

        // We don't use the settings here explicitly, since HttpRequests picks up the network settings from studio directly.
        ProgressHandle handle = ProgressHandle.createHandle("Downloading " + url);
        try {
            URLConnection connection = url.openConnection();
            if (connection instanceof HttpsURLConnection) {
                ((HttpsURLConnection) connection).setInstanceFollowRedirects(true);
                ((HttpsURLConnection) connection).setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
                ((HttpsURLConnection) connection).setRequestProperty("Accept-Charset", "UTF-8");
                ((HttpsURLConnection) connection).setDoOutput(true);
                ((HttpsURLConnection) connection).setDoInput(true);
            }
            connection.setConnectTimeout(3000);
            connection.connect();
            int contentLength = connection.getContentLength();
            if (contentLength < 1) {
                throw new FileNotFoundException();
            }
            handle.start(contentLength);
            OutputStream dest = new FileOutputStream(target);
            InputStream in = connection.getInputStream();
            int count;
            int done = 0;
            byte data[] = new byte[BUFFER_SIZE];
            while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
                done += count;
                handle.progress(done);
                dest.write(data, 0, count);
            }
            dest.close();
            in.close();
        } finally {
            handle.finish();
            if (target.length() == 0) {
                try {
                    target.delete();
                } catch (Exception e) {
                }
            }
        }
    }
 
Example 14
Source File: FileOperation.java    From Android-POS with MIT License 4 votes vote down vote up
public boolean comparefileSize(String localfilename,String remoteurl){
	long localfile = 0;
	long remotefile = 0;
	
	long lastmodifylocal = 0;
	long lastmodifyremote = 0;
	try{
		if(localfilename != null && remoteurl != null){
			  File fl = ct.getFileStreamPath( localfilename );
			  if(fl.exists()){
				  localfile = fl.length();
				  lastmodifylocal = fl.lastModified();
			  }else{
				  localfile = 0;
				  return false;
			  }
			  
			  URLConnection connect = null;
			  URL newUrl=new URL(remoteurl);
			  connect=newUrl.openConnection();
			  connect.setRequestProperty ("Content-type","application/x-www-form-urlencoded");
			  
			  connect.connect();
			  
			 
			
			  remotefile = connect.getContentLength();
			  lastmodifyremote = connect.getLastModified();
			  Log.i("local file size",localfile+"");
			  Log.i("remote file size",remotefile + "");
			  
			  Log.i("last modify local ",lastmodifylocal+"");
			  Log.i("last modify remote ",lastmodifyremote + "");
			  
			  if(localfile == remotefile){
				  return true;
			  }else{
				  return false;
			  }
		}else{
			return false;
		}
	}catch(Exception e){
		e.printStackTrace();
		return false;
	}
}
 
Example 15
Source File: URLDownloader.java    From Flashtool with GNU General Public License v3.0 4 votes vote down vote up
public long Download(String strurl, String filedest, long seek) throws IOException {
	try {
		// Setup connection.
        URL url = new URL(strurl);
        URLConnection connection = url.openConnection();
        
        File fdest = new File(filedest);
        connection.connect();
        mDownloaded = 0;
        mFileLength = connection.getContentLength();
        strLastModified = connection.getHeaderField("Last-Modified");
        Map<String, List<String>> map = connection.getHeaderFields();

        // Setup streams and buffers.
        int chunk = 131072;
        input = new BufferedInputStream(connection.getInputStream(), chunk);
        outFile = new RandomAccessFile(fdest, "rw");
        outFile.seek(seek);
        
        byte data[] = new byte[chunk];
        LogProgress.initProgress(100);
        long i=0;
        // Download file.
        for (int count=0; (count=input.read(data, 0, chunk)) != -1; i++) { 
            outFile.write(data, 0, count);
            mDownloaded += count;
            
            LogProgress.updateProgressValue((int) (mDownloaded * 100 / mFileLength));
            if (mDownloaded >= mFileLength)
                break;
            if (canceled) break;
        }
        // Close streams.
        outFile.close();
        input.close();
        return mDownloaded;
	}
	catch (IOException ioe) {
		try {
			outFile.close();
		} catch (Exception ex1) {}
		try {
			input.close();
		} catch (Exception ex2) {}
		if (canceled) throw new IOException("Job canceled");
		throw ioe;
	}
}
 
Example 16
Source File: ArchiveReaderFactory.java    From webarchive-commons with Apache License 2.0 4 votes vote down vote up
protected ArchiveReader makeARCLocal(final URLConnection connection)
throws IOException {
    File localFile = null;
    if (connection instanceof HttpURLConnection) {
        // If http url connection, bring down the resource local.
        String p = connection.getURL().getPath();
        int index = p.lastIndexOf('/');
        if (index >= 0) {
            // Name file for the file we're making local.
            localFile = File.createTempFile("",p.substring(index + 1));
            if (localFile.exists()) {
                // If file of same name already exists in TMPDIR, then
                // clean it up (Assuming only reason a file of same name in
                // TMPDIR is because we failed a previous download).
                localFile.delete();
            }
        } else {
            localFile = File.createTempFile(ArchiveReader.class.getName(),
                ".tmp");
        }
        addUserAgent((HttpURLConnection)connection);
        connection.connect();
        try {
            FileUtils.readFullyToFile(connection.getInputStream(), localFile);
        } catch (IOException ioe) {
            localFile.delete();
            throw ioe;
        }
    } else if (connection instanceof RsyncURLConnection) {
        // Then, connect and this will create a local file.
        // See implementation of the rsync handler.
        connection.connect();
        localFile = ((RsyncURLConnection)connection).getFile();
    } else if (connection instanceof Md5URLConnection) {
        // Then, connect and this will create a local file.
        // See implementation of the md5 handler.
        connection.connect();
        localFile = ((Md5URLConnection)connection).getFile();
    } else {
        throw new UnsupportedOperationException("No support for " +
            connection);
    }
    
    ArchiveReader reader = null;
    try {
        reader = get(localFile, 0);
    } catch (IOException e) {
        localFile.delete();
        throw e;
    }
    
    // Return a delegate that does cleanup of downloaded file on close.
    return reader.getDeleteFileOnCloseReader(localFile);
}
 
Example 17
Source File: Exchange.java    From libdynticker with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected JsonNode readJsonFromUrl(String url) throws IOException {
	URLConnection urlConnection = buildConnection(url);
	urlConnection.connect();
	return mapper.readTree(urlConnection.getInputStream());
}
 
Example 18
Source File: URLResourceRetriever.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public InputStream getInputStreamOfURL(URL downloadURL, Proxy proxy) throws IOException{
    
    URLConnection ucn = null;
    
    // loop until no more redirections are 
    for (;;) {
        if (Thread.currentThread().isInterrupted()) {
            return null;
        }
        if(proxy != null) {
            ucn = downloadURL.openConnection(proxy);
        } else {
            ucn = downloadURL.openConnection();
        }
        HttpURLConnection hucn = doConfigureURLConnection(ucn);

        if(Thread.currentThread().isInterrupted())
            return null;
    
        ucn.connect();

        int rc = hucn.getResponseCode();
        boolean isRedirect = 
                rc == HttpURLConnection.HTTP_MOVED_TEMP ||
                rc == HttpURLConnection.HTTP_MOVED_PERM;
        if (!isRedirect) {
            break;
        }

        String addr = hucn.getHeaderField(HTTP_REDIRECT_LOCATION);
        URL newURL = new URL(addr);
        if (!downloadURL.getProtocol().equalsIgnoreCase(newURL.getProtocol())) {
            throw new ResourceRedirectException(newURL);
        }
        downloadURL = newURL;
    }

    ucn.setReadTimeout(10000);
    InputStream is = ucn.getInputStream();
    streamLength = ucn.getContentLength();
    effectiveURL = ucn.getURL();
    return is;
    
}
 
Example 19
Source File: MapReduceFetcherHadoop2.java    From dr-elephant with Apache License 2.0 4 votes vote down vote up
private void verifyURL(String url) throws IOException {
  final URLConnection connection = new URL(url).openConnection();
  // Check service availability
  connection.connect();
  return;
}
 
Example 20
Source File: NetworkAdminHTTPTester.java    From BiglyBT with GNU General Public License v2.0 2 votes vote down vote up
@Override
public InetAddress
testOutbound(
	InetAddress		bind_ip,
	int				bind_port,
	boolean			ipv6 )

	throws NetworkAdminException
{
	if ( bind_ip != null || bind_port != 0 ){

		throw( new NetworkAdminException("HTTP tester doesn't support local bind options"));
	}

	try{
			// 	try to use our service first

		return( VersionCheckClient.getSingleton().getExternalIpAddressHTTP(false));

	}catch( Throwable e ){

			// fallback to something else

		try{
				// TODO: V6
			
			URL	url = new URL( "http://www.google.com/" );

			URLConnection connection = url.openConnection();

			connection.setConnectTimeout( 10000 );

			connection.connect();

			return( null );

		}catch( Throwable f ){

			throw( new NetworkAdminException( "Outbound test failed", e ));
		}
	}
}