重写URLConnection的getInputStream以通过自定义协议接收数据

时间:2018-08-07 08:29:28

标签: java inputstream java-web-start jnlp urlconnection

我正在使用Java Web Start抓取并启动应用程序,为此,我必须通过所谓的jnlp协议下载数据。由于默认情况下Java不知道该协议,因此我必须编写自己的URL流处理程序。

我的问题是我不知道如何实现getInputStream方法,

// the custom URL stream handler
URL.setURLStreamHandlerFactory((String protocol)
    -> "jnlp".equals(protocol) ? new URLStreamHandler() {
    @Override
    protected URLConnection openConnection(URL url) throws IOException {
        return new URLConnection(url) {
            @Override
            public void connect() throws IOException {
                System.out.println("connected");
            }
            @Override
            public InputStream getInputStream() throws IOException {
                /* -------------------- */
                /* What to put in here? */
                /* -------------------- */
            }
        };
    }
} : null);

// Constructing the parametrized URL for Java Web Start...
URL url = new URL("jnlp", "localhost", 8080,
    "application-connector/app?"
    + params.entrySet().stream().map(Object::toString)
        .collect(joining("&")));

// Downloading and starting the application...
final File jnlp = File.createTempFile("temp", ".jnlp");
byte[] buffer = new byte[8192];
int len;
while ((len = url.openStream().read(buffer)) != -1) {
    new FileOutputStream(jnlp).write(buffer, 0, len);
}
Desktop.getDesktop().open(jnlp);

这是必要的,这样我就不会出现以下错误:

  

协议不支持输入

1 个答案:

答案 0 :(得分:1)

通常,可以从http:/ https:URL下载JNLP。例如。 :

    URL url = new URL(
            "https://docs.oracle.com/javase/tutorialJWS/samples/uiswing/WallpaperProject/Wallpaper.jnlp");

    // Downloading and starting the application...
    final File jnlp = File.createTempFile("temp", ".jnlp");

    try (InputStream is = url.openStream();
            FileOutputStream fos = new FileOutputStream(jnlp)) {
        byte[] buffer = new byte[8192];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
    }

    System.out.println("JNLP file written to " + jnlp.getAbsolutePath());

    //Desktop.getDesktop().open(jnlp);
    new ProcessBuilder("cmd", "/c", "javaws", jnlp.getAbsolutePath())
            .start();

不确定用于此环境。在Windows下,我发现Desktop.open()没有启动,因此直接调用javaws

如果可以选择直接调用javaws,则有一种更简单的方法,因为它可以直接从URL启动JNLP文件:

    new ProcessBuilder("cmd", "/c", "javaws",
            "https://docs.oracle.com/javase/tutorialJWS/samples/uiswing/WallpaperProject/Wallpaper.jnlp")
                    .start();