how to unset ContentHandlerFactory in HTTPUrlConnection
HTTPUrlConnection.setContentHandlerFactory()
method throws Excep开发者_如何学运维tion saying factory is already defined. I understand that. Is it possible to unset the factory and change the contenthandler factory?
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.
精彩评论