当前位置: 首页>>代码示例>>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;未经允许,请勿转载。