注册和使用自定义 java.net.URL 协议
我试图从我的java程序中调用一个,因此我使用了这样的东西:custom url
URL myURL;
try {
myURL = new URL("CustomURI:");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
} catch (Exception e) {
e.printStackTrace();
}
我得到了以下异常:
java.net.MalformedURLException: unknown protocol: CustomURI at java.net.URL.(未知来源)在java.net.URL。(未知来源)在java.net.URL。(未知来源)在com.demo.TestDemo.main(TestDemo.java:14)
如果我从浏览器触发,那么它按预期工作,但如果我尝试从调用它,那么我就会得到上述异常。URI
Java Program
编辑:
以下是我尝试过的步骤(我肯定错过了一些东西,请让我知道):
步骤 1:在 java.protocol.handler.pkgs
中添加自定义 URI
步骤 2:从 URL 触发自定义 URI
法典:
public class CustomURI {
public static void main(String[] args) {
try {
add("CustomURI:");
URL uri = new URL("CustomURI:");
URLConnection uc = uri.openConnection();
uc.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void add( String handlerPackage ){
final String key = "java.protocol.handler.pkgs";
String newValue = handlerPackage;
if ( System.getProperty( key ) != null )
{
final String previousValue = System.getProperty( key );
newValue += "|" + previousValue;
}
System.setProperty( key, newValue );
System.out.println(System.getProperty("java.protocol.handler.pkgs"));
}
}
当我运行此代码时,我正在我的控制台(从 add 方法)中获取打印的代码,但是当 使用 构造函数初始化时,我会收到此异常:CustomURI:
URL
CustomURI:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at java.net.URL.getURLStreamHandler(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at sun.misc.URLClassPath$FileLoader.getResource(Unknown Source)
at sun.misc.URLClassPath.getResource(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.net.URL.getURLStreamHandler(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
请建议如何使这项工作。