java.net.URLConnection#connect ( )源码实例Demo

下面列出了java.net.URLConnection#connect ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: FacebookNewsfeedSample-Android   文件: Utility.java
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;
}
 
源代码2 项目: TorrentEngine   文件: TrackerLoadTester.java
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();
  }    
}
 
@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);
}
 
@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;
}
 
/**
 * 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);
        }
    }
}
 
源代码6 项目: SENS   文件: SensUtils.java
/**
 * 访问路径获取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;
}
 
源代码7 项目: wildfly-core   文件: DeploymentPlanBuilderImpl.java
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) {}
    }
}
 
@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;
    }

}
 
源代码9 项目: HotswapAgent   文件: Viewer.java
/**
 * 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;
}
 
源代码10 项目: onos   文件: GluonServerCommand.java
/**
 * 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;
}
 
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();
}
 
源代码12 项目: Beedio   文件: VideoContentSearch.java
@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);
}
 
源代码13 项目: Android-POS   文件: FileOperation.java
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;
	}
}
 
源代码14 项目: dr-elephant   文件: MapReduceFetcherHadoop2.java
private void verifyURL(String url) throws IOException {
  final URLConnection connection = new URL(url).openConnection();
  // Check service availability
  connection.connect();
  return;
}
 
源代码15 项目: Flashtool   文件: URLDownloader.java
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;
	}
}
 
源代码16 项目: NBANDROID-V2   文件: MavenDownloader.java
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) {
                }
            }
        }
    }
 
源代码17 项目: webarchive-commons   文件: ArchiveReaderFactory.java
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);
}
 
源代码18 项目: libdynticker   文件: Exchange.java
protected JsonNode readJsonFromUrl(String url) throws IOException {
	URLConnection urlConnection = buildConnection(url);
	urlConnection.connect();
	return mapper.readTree(urlConnection.getInputStream());
}
 
源代码19 项目: netbeans   文件: URLResourceRetriever.java
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;
    
}
 
源代码20 项目: BiglyBT   文件: NetworkAdminHTTPTester.java
@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 ));
		}
	}
}