java - 覆盖 URLConnection 的 getInputStream 以通过自定义协议接收数据
问题描述
我正在使用 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);
这是必要的,所以我不会收到以下错误:
协议不支持输入
解决方案
通常可以从 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();
推荐阅读
- vue.js - configureWebpack 功能模式 如何配置 unplugin-vue-components 插件?
- windows - 通过 Windows 10 的上下文菜单将选定的多个文件名传递给 exe 文件的单个实例
- google-api - 在 Google Campaign 360 中调用 conversions.batchInsert 时出现“找不到 MatchID”错误
- opencv - opencv_annotation(-204:未找到请求的对象)
- c# - WebApi 部署问题应用程序'MACHINE/WEBROOT/APPHOST/
- matlab - 无法在 MATLAB 中创建符号变量 n 行 1 列
- forms - 是否可以在 MS 表单中显示自定义文本超链接?
- c++ - 如何将此 JavaScript 代码转换为 C++
- javascript - 防止点击 React-Fiber Three.js 中的对象
- python - 如何在python中计算汇总值