Skip to content
Advertisement

Setting connection properties on the URL object

Question: Is there a way to set the connection properties on the URL object?


Background:
We are connecting to a remote server that requires certain connection properties to be set (e.g. User-Agent but certain proprietary properties as well). We are currently using the setRequestProperty method on the URLConnection object for this purpose. So far so good. Now we want to use an API that requires the URL object. We have not been able to figure out how to set the connection request properties on a URL object. As a result the remote server is rejecting the API call with response code 403.

Any pointers will be appreciated.

FYI urlConnObject.getURL() did not do the trick and the server rejected the call with 403 error code.

Advertisement

Answer

Question: Is there a way to set the connection properties on the URL object?

Answer: There is no way.

A Java URL or URI object does not have connection properties, or any way to represent them.

Connection properties are supported by the APIs that actually establish a connection; e.g. java.net.URLConnection and its subtypes, Java 11+ java.net.http.HttpClient and various 3rd-party HTTP client libraries.


Here are a couple of ideas that may help:

  • You could construct a Map<URL, Map<String, String>> that associates URLs with sets of connection properties, by that is rather inflexible and there is potential for memory leaks if the map is long-lived.

  • You could create a custom class that represents “target” web object as a URL and a collection of connection properties and … other relevant things.

The best solution will depend on what you are actually trying to achieve, and your application’s internal architecture.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement