gpt4 book ai didi

java - 为 URLStreamHandlerFactory 创建 HttpURLConnection,出现错误 : protocol doesn't support input

转载 作者:可可西里 更新时间:2023-11-01 16:37:40 27 4
gpt4 key购买 nike

一些背景知识,我正在尝试创建一个 URL 流处理程序,以便我可以跟踪在我的 javafx 应用程序中我的 webview 上有多少 Activity 连接。本质上,我在 WebView 中运行 AngularJs 应用程序,我想知道它何时完成。我不能触摸网站代码,所以添加一个 js 通知程序不在桌面上。所以,无论我把什么放在一起,设置总是出现“协议(protocol)不支持输入”的错误。我试图用只返回 false 的方法覆盖“getDoInput”,但我仍然收到错误。有什么想法吗?

这是接近我正在做的事情:

public class MyUrlStreamHandlerFactory implements URLStreamHandlerFactory {

public URLStreamHandler createURLStreamHandler(String protocol) {
if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) {

return new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL url) throws IOException {

return new HttpURLConnection(url) {
@Override
public void connect() throws IOException {

}

@Override
public void disconnect() {

}

@Override
public boolean usingProxy() {
return false;
}

@Override
public boolean getDoInput() {
return false;
}
};

}
};

}
return null;
}
}

我正在安装它:

URL.setURLStreamHandlerFactory(new MyUrlStreamHandlerFactory());

最佳答案

我理解你想要完成的事情,但是我认为这是错误的方法。

From: Java Network Programming by Elliotte Rusty Harold

Only abstract URLConnection classes are present in the java.net package. The concrete subclasses are hidden inside the sun.net package hierarchy. It is rare to instantiate URLConnection objects directly in your source code; instead, the runtime environment creates these objects as needed, depending on the protocol in use. The class (which is unknown at compile time) is then instantiated using the forName() and newInstance() methods of the java.lang.Class class.

For example, the connect() method of sun.net.www.protocol.http.HttpURLConnection creates a sun.net.www.http.HttpClient object, which is responsible for connecting to the server.

因此,除非您想编写自己的 http 协议(protocol)处理程序和 HttpClient,否则我建议探索其他途径。

其他

我能找到的唯一抛出 UnknownServiceException 消息为 "protocol doesn't support input" 的方法是:

java.net.URLConnection#getInputStream

/**
* Returns an input stream that reads from this open connection.
*
* @return an input stream that reads from this open connection.
* @exception IOException if an I/O error occurs while
* creating the input stream.
* @exception UnknownServiceException if the protocol does not support
* input.
*/
public InputStream getInputStream() throws IOException {
throw new UnknownServiceException("protocol doesn't support input");
}

覆盖 getDoInput
您不应覆盖 getDoInput 以仅返回 false。相反,您应该使用 setDoInput(false)。但是,您不想将 doInput 设置为 false。你总是想读一些东西,例如响应代码。

关于java - 为 URLStreamHandlerFactory 创建 HttpURLConnection,出现错误 : protocol doesn't support input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27993995/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com