views:

59

answers:

1

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?

+1  A: 

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.

Ash
I tried your suggestion, but it still trows the same factory already defined Error.
artsince
@artsince: I don't have any such problem. You should note that my snippet above is actually setting a new factory instance. If you want to "reset" it to null (so you can call `setContentHandlerFactory` again), you should do: `factoryField.set( null, null );`
Ash
yes, actually I had set the field to null first. I might have another problem if this method works for you...
artsince
What JDK are you using? Are you using any third-party libraries?
Ash
I am using a Third-Party library. I use 1.6 compatible with 1.5.
artsince
Can you edit your question to include a (short) runnable example that demonstrates the problem? I think at this point more details are needed in order to help any further.
Ash