如何在 HTTPUrlConnection 中取消设置 ContentHandlerFactory

发布于 2024-08-30 20:34:41 字数 108 浏览 2 评论 0原文

HTTPUrlConnection.setContentHandlerFactory()方法抛出异常,表示工厂已定义。我明白这一点。是否可以取消设置工厂并更改内容处理程序工厂?

HTTPUrlConnection.setContentHandlerFactory()method throws Exception saying factory is already defined. I understand that. Is it possible to unset the factory and change the contenthandler factory?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

活泼老夫 2024-09-06 20:34:41

URLConnectionHttpURLConnection 的超类)中的 factory 字段是一个静态包访问成员变量。通过 API 修改它的唯一地方是 setContentHandlerFactory() 方法,正如您所注意到的,您只能对应用程序中的任何 URL 连接(或子类)调用它一次。

我相信有一种解决方法,但这并不理想:您可以使用反射重置和/或更改 factory 字段的值(假设您的应用程序具有适当的安全管理器权限来使 字段可访问) 。

下面是执行此操作的代码片段:

ContentHandlerFactory newFactory = ... // create factory instance
factoryField = URLConnection.class.getDeclaredField( "factory" );
factoryField.setAccessible( true );
factoryField.set( null, newFactory );

这样做的问题是 API 不希望发生这种情况,因此可能会产生不需要的副作用(因为它适用于所有 URL 连接子类)。基本上,您将自行承担风险。

The factory field in URLConnection (the superclass of HttpURLConnection) is a static package access member variable. The only place it's modified via the API is the setContentHandlerFactory() method, and as you've noted you can only call it once for any URL connection (or subclass) in the application.

I believe there is a way around it, but it's hardly ideal: You can reset and/or change the value of the factory field using reflection (assuming your application has appropriate security manager privileges to make the field accessible).

Here's a snippet that will do so:

ContentHandlerFactory newFactory = ... // create factory instance
factoryField = URLConnection.class.getDeclaredField( "factory" );
factoryField.setAccessible( true );
factoryField.set( null, newFactory );

The problem with this is that the API doesn't expect this will ever happen, so there may be unwanted side effects (since it applies to all URL connection subclasses). Basically you would be doing it at your own risk.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文