當前位置: 首頁>>代碼示例>>Java>>正文


Java URL.getProtocol方法代碼示例

本文整理匯總了Java中java.net.URL.getProtocol方法的典型用法代碼示例。如果您正苦於以下問題:Java URL.getProtocol方法的具體用法?Java URL.getProtocol怎麽用?Java URL.getProtocol使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.net.URL的用法示例。


在下文中一共展示了URL.getProtocol方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: exists

import java.net.URL; //導入方法依賴的package包/類
public static boolean exists(URL url) {
    switch (url.getProtocol()) {
    case "file":
        try {
            File actualFile = new File(url.toURI());
            return actualFile.exists();
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
    case "jar":
        try {
            URLConnection conn = url.openConnection();
            conn.getInputStream().close();
            return true;
        } catch (IOException | StringIndexOutOfBoundsException ex) {
            return false;
        }
    default:
    }
    return false;
}
 
開發者ID:salesforce,項目名稱:grammaticus,代碼行數:22,代碼來源:TrackingHandler.java

示例2: getHostAndPort

import java.net.URL; //導入方法依賴的package包/類
private String getHostAndPort(URL url) {
    String host = url.getHost();
    final String hostarg = host;
    try {
        // lookup hostname and use IP address if available
        host = AccessController.doPrivileged(
            new PrivilegedExceptionAction<String>() {
                public String run() throws IOException {
                        InetAddress addr = InetAddress.getByName(hostarg);
                        return addr.getHostAddress();
                }
            }
        );
    } catch (PrivilegedActionException e) {}
    int port = url.getPort();
    if (port == -1) {
        String scheme = url.getProtocol();
        if ("http".equals(scheme)) {
            return host + ":80";
        } else { // scheme must be https
            return host + ":443";
        }
    }
    return host + ":" + Integer.toString(port);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:26,代碼來源:HttpURLConnection.java

示例3: handleRedirect

import java.net.URL; //導入方法依賴的package包/類
/**
 * Handles a redirect.
 *
 * @param originalUrl The original URL.
 * @param location    The Location header in the response.
 * @return The next URL.
 * @throws IOException If redirection isn't possible.
 */
private static URL handleRedirect(URL originalUrl, String location) throws IOException {
    if (location == null) {
        throw new ProtocolException("Null location redirect");
    }
    // Form the new url.
    URL url = new URL(originalUrl, location);
    // Check that the protocol of the new url is supported.
    String protocol = url.getProtocol();
    if (!"https".equals(protocol) && !"http".equals(protocol)) {
        throw new ProtocolException("Unsupported protocol redirect: " + protocol);
    }
    // Currently this method is only called if allowCrossProtocolRedirects is true, and so the code
    // below isn't required. If we ever decide to handle redirects ourselves when cross-protocol
    // redirects are disabled, we'll need to uncomment this block of code.
    // if (!allowCrossProtocolRedirects && !protocol.equals(originalUrl.getProtocol())) {
    //   throw new ProtocolException("Disallowed cross-protocol redirect ("
    //       + originalUrl.getProtocol() + " to " + protocol + ")");
    // }
    return url;
}
 
開發者ID:PhoenixDevTeam,項目名稱:Phoenix-for-VK,代碼行數:29,代碼來源:CustomHttpDataSource.java

示例4: validURL

import java.net.URL; //導入方法依賴的package包/類
private boolean validURL(String urlPath) {
    try {
        URL url = new URL(urlPath);
        String protocol = url.getProtocol();
        return protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https");
    } catch (MalformedURLException e) {
    }
    return false;
}
 
開發者ID:jalian-systems,項目名稱:marathonv5,代碼行數:10,代碼來源:JavaProfile.java

示例5: sameFile

import java.net.URL; //導入方法依賴的package包/類
@Override
protected boolean sameFile(URL u1, URL u2) {
    // Compare the protocols.
    if (!((u1.getProtocol() == u2.getProtocol()) ||
          (u1.getProtocol() != null &&
           u1.getProtocol().equalsIgnoreCase(u2.getProtocol()))))
        return false;

    // Compare the files.
    if (!(u1.getFile() == u2.getFile() ||
          (u1.getFile() != null && u1.getFile().equals(u2.getFile()))))
        return false;

    // Compare the hosts.
    if (!hostsEqual(u1, u2))
        return false;

    return true;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:20,代碼來源:NbinstURLStreamHandler.java

示例6: isValid

import java.net.URL; //導入方法依賴的package包/類
/**
 *  A valid URL must have values for protocol and host.
 *
 * @param  url  A URL instance
 * @return      true if the URL has both a protocal and host
 * @see         java.net.URL
 */
public static boolean isValid(URL url) {

	try {
		String protocol = url.getProtocol();
		String host = url.getHost();
		String path = url.getPath();
		boolean ret = ((protocol != null && protocol.trim().length() > 0) &&
			(host != null && host.trim().length() > 0));
		// prtln ("  isValid (" + url.toString() + ") : " + ret);
		return ret;
	} catch (Throwable t) {
		prtln("isValid error: " + t.getMessage());
		return false;
	}
}
 
開發者ID:NCAR,項目名稱:joai-project,代碼行數:23,代碼來源:UrlHelper.java

示例7: updateMediaNotificationForTab

import java.net.URL; //導入方法依賴的package包/類
/**
 * Send an intent to MediaCaptureNotificationService to either create, update or destroy the
 * notification identified by tabId.
 * @param tabId Unique notification id.
 * @param mediaType The media type that is being captured.
 * @param fullUrl Url of the current webrtc call.
 */
public static void updateMediaNotificationForTab(
        Context context, int tabId, int mediaType, String fullUrl) {
    if (!shouldStartService(context, mediaType, tabId)) return;
    Intent intent = new Intent(context, MediaCaptureNotificationService.class);
    intent.setAction(ACTION_MEDIA_CAPTURE_UPDATE);
    intent.putExtra(NOTIFICATION_ID_EXTRA, tabId);
    String baseUrl = fullUrl;
    try {
        URL url = new URL(fullUrl);
        baseUrl = url.getProtocol() + "://" + url.getHost();
    } catch (MalformedURLException e) {
        Log.w(TAG, "Error parsing the webrtc url, %s ", fullUrl);
    }
    intent.putExtra(NOTIFICATION_MEDIA_URL_EXTRA, baseUrl);
    intent.putExtra(NOTIFICATION_MEDIA_TYPE_EXTRA, mediaType);
    context.startService(intent);
}
 
開發者ID:rkshuai,項目名稱:chromium-for-android-56-debug-video,代碼行數:25,代碼來源:MediaCaptureNotificationService.java

示例8: parseURL

import java.net.URL; //導入方法依賴的package包/類
/**
 * This method is called to parse the string spec into URL u for a
 * mailto protocol.
 *
 * @param   u the URL to receive the result of parsing the spec
 * @param   spec the URL string to parse
 * @param   start the character position to start parsing at.  This is
 *          just past the ':'.
 * @param   limit the character position to stop parsing at.
 */
public void parseURL(URL u, String spec, int start, int limit) {

    String protocol = u.getProtocol();
    String host = "";
    int port = u.getPort();
    String file = "";

    if (start < limit) {
        file = spec.substring(start, limit);
    }
    /*
     * Let's just make sure we DO have an Email address in the URL.
     */
    boolean nogood = false;
    if (file == null || file.equals(""))
        nogood = true;
    else {
        boolean allwhites = true;
        for (int i = 0; i < file.length(); i++)
            if (!Character.isWhitespace(file.charAt(i)))
                allwhites = false;
        if (allwhites)
            nogood = true;
    }
    if (nogood)
        throw new RuntimeException("No email address");
    setURLHandler(u, protocol, host, port, file, null);
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:39,代碼來源:Handler.java

示例9: retrieveRemoteImage

import java.net.URL; //導入方法依賴的package包/類
protected void retrieveRemoteImage(final TextureTile tile, String mimeType, int timeout) throws Exception
{
    // TODO: apply retriever-factory pattern for remote retrieval case.
    final URL resourceURL = tile.getResourceURL(mimeType);
    if (resourceURL == null)
        return;

    Retriever retriever;

    String protocol = resourceURL.getProtocol();

    if ("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol))
    {
        retriever = new HTTPRetriever(resourceURL, new CompositionRetrievalPostProcessor(tile));
        retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy layers
    }
    else
    {
        String message = Logging.getMessage("layers.TextureLayer.UnknownRetrievalProtocol", resourceURL);
        throw new RuntimeException(message);
    }

    Logging.logger().log(java.util.logging.Level.FINE, "Retrieving " + resourceURL.toString());
    retriever.setConnectTimeout(10000);
    retriever.setReadTimeout(timeout);
    retriever.call();
}
 
開發者ID:iedadata,項目名稱:geomapapp,代碼行數:28,代碼來源:ScalingTiledImageLayer.java

示例10: getScaledImageURL

import java.net.URL; //導入方法依賴的package包/類
private static URL getScaledImageURL(URL url) {
    try {
        String scaledImagePath = getScaledImageName(url.getPath());
        return scaledImagePath == null ? null : new URL(url.getProtocol(),
                url.getHost(), url.getPort(), scaledImagePath);
    } catch (MalformedURLException e) {
        return null;
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:10,代碼來源:LWCToolkit.java

示例11: getServletURL

import java.net.URL; //導入方法依賴的package包/類
public static URL getServletURL () throws MalformedURLException, UnknownHostException {
    
    URL base = getSampleHTTPServerURL();
    // XXX hack: assume that the path /servlet/CLASSNAME works on this server.
    URL root = new URL (base.getProtocol(), base.getHost(), base.getPort(), "/servlet/" + TransformServlet.class.getName() + "/");
    
    return root;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:9,代碼來源:TransformServlet.java

示例12: toPath

import java.net.URL; //導入方法依賴的package包/類
/**
 * Convert a local URL (file:// or jar:// protocol) to a {@link Path}
 * @param resource the URL resource
 * @return the Path
 * @throws URISyntaxException
 * @throws IOException
 */
public static Path toPath(URL resource) throws IOException, URISyntaxException {
    if (resource == null) return null;

    final String protocol = resource.getProtocol();
    if ("file".equals(protocol)) {
        return Paths.get(resource.toURI());
    } else if ("jar".equals(protocol)) {
        final String s = resource.toString();
        final int separator = s.indexOf("!/");
        final String entryName = s.substring(separator + 2);
        final URI fileURI = URI.create(s.substring(0, separator));

        final FileSystem fileSystem;
        if (!jarFileSystems.contains(fileURI))
            synchronized (jarFileSystems) {
                if (jarFileSystems.add(fileURI)) {
                    fileSystem = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap());
                } else {
                    fileSystem = FileSystems.getFileSystem(fileURI);
                }
            } else {
            fileSystem = FileSystems.getFileSystem(fileURI);
        }
        return fileSystem.getPath(entryName);
    } else {
        throw new IllegalArgumentException("Can't read " + resource + ", unknown protocol '" + protocol + "'");
    }
}
 
開發者ID:redlink-gmbh,項目名稱:smarti,代碼行數:36,代碼來源:FileSystemUtils.java

示例13: openFileURLStream

import java.net.URL; //導入方法依賴的package包/類
/**
 * Returns an InputStream the given url if the url has a protocol of 'file' or 'jar', no host, and no port.
 */
@SuppressForbidden(reason = "Will only open url streams for local files")
public static InputStream openFileURLStream(URL url) throws IOException {
    String protocol = url.getProtocol();
    if ("file".equals(protocol) == false && "jar".equals(protocol) == false) {
        throw new IllegalArgumentException("Invalid protocol [" + protocol + "], must be [file] or [jar]");
    }
    if (Strings.isEmpty(url.getHost()) == false) {
        throw new IllegalArgumentException("URL cannot have host. Found: [" + url.getHost() + ']');
    }
    if (url.getPort() != -1) {
        throw new IllegalArgumentException("URL cannot have port. Found: [" + url.getPort() + ']');
    }
    return url.openStream();
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:18,代碼來源:FileSystemUtils.java

示例14: _getClassName

import java.net.URL; //導入方法依賴的package包/類
/**
 * 獲取某包下所有類.
 * URLDecoder.decode(url.getFile(),ENCODING):對中文的支持
 *
 * @param packageName  包名
 * @param childPackage 是否遍曆子包
 * @return 類的完整名稱
 */
private static List<String> _getClassName(String packageName, ClassLoader classLoader,
        boolean childPackage) throws UnsupportedEncodingException
{
    List<String> fileNames = null;
    ClassLoader loader = classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader();
    String packagePath = packageName.replace('.', '/');
    URL url = loader.getResource(packagePath);
    if (url != null)
    {
        String type = url.getProtocol();
        //LogUtil.printLnPos(url);
        if (type.equals("file"))
        {
            fileNames = getClassNameByFile(packageName, URLDecoder.decode(url.getFile(), ENCODING), childPackage);
        } else if (type.equals("jar"))
        {
            fileNames = getClassNameByJar(URLDecoder.decode(url.getFile(), ENCODING), childPackage);
        }
    } else
    {
        if (loader instanceof IClassLoader)
        {
            IClassLoader iClassLoader = (IClassLoader) loader;
            iClassLoader.seek();
            fileNames = iClassLoader.getClassNames(packageName, childPackage);
            iClassLoader.release();
        } else
        {
            fileNames = getClassNameByJars(getUrls(loader, packageName), packagePath, childPackage);
        }

    }
    return fileNames;
}
 
開發者ID:gzxishan,項目名稱:OftenPorter,代碼行數:43,代碼來源:PackageUtil.java

示例15: getBeanClassListIterate

import java.net.URL; //導入方法依賴的package包/類
public List<Class<?>> getBeanClassListIterate(String packageName) {
  	
  	List<Class<?>> classList = new ArrayList<Class<?>>();
  	Enumeration<URL> urls = null;
  	
  	try {
	urls = ClassUtil.getClassLoader().getResources(packageName.replace(".", "/"));
} catch (IOException e1) {
	e1.printStackTrace();
}
  	
      // 遍曆 URL 資源
      while (urls.hasMoreElements()) {
          URL url = urls.nextElement();
          if (url != null) {
              // 獲取協議名(分為 file 與 jar)
              String protocol = url.getProtocol();
              if (protocol.equals("file")) {
                  // 若在 class 目錄中,則執行添加類操作
                  String packagePath = url.getPath();
                  addClass(classList, packagePath, packageName);
              } else if (protocol.equals("jar")) {

			try {
                   // 若在 jar 包中,則解析 jar 包中的 entry
                   JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                   JarFile jarFile = jarURLConnection.getJarFile();
				
                   Enumeration<JarEntry> jarEntries = jarFile.entries();
                   while (jarEntries.hasMoreElements()) {
                       JarEntry jarEntry = jarEntries.nextElement();
                       String jarEntryName = jarEntry.getName();
                       // 判斷該 entry 是否為 class
                       if (jarEntryName.endsWith(".class")) {
                           // 獲取類名
                           String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                           // 執行添加類操作
                           doAddClass(classList, className);
                       }
                   }						
				
			} catch (IOException e) {
				e.printStackTrace();
			}

              }
          }
      }    	
  	
      return classList;
      
  }
 
開發者ID:smxc,項目名稱:garlicts,代碼行數:53,代碼來源:BeanLoaderTemplate.java


注:本文中的java.net.URL.getProtocol方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。