简体   繁体   中英

How to set default HTTP User Agent from a Java Web Start application?

We define in our Java application a custom HTTP User-Agent containing the following:

  1. Software version
  2. User language
  3. Platform information (operating system family + release name)
  4. Java version

We want this user agent to be applied to all HTTP connections created by the application, including those we open manually, but also those automatically created by the JRE, for example when a JEditorPane resolves external images referenced inside HTML code.

For this, we set the "http.agent" system property to points 1/2/3 (letting the JRE add by itself the Java version ) at the startup of our application:

System.setProperty("http.agent", Version.getAgentString());

This works great when we run the application from a jar, but not from Java Web Start.

As a workaround, we manually set our full User-Agent to the connections we create manually:

public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
    connection.setRequestProperty("User-Agent", Version.getFullAgentString());
    return connection;
}

But this does not handle the case where the connection is created by the JRE (JEditorPane example).

How can we set the user agent in this case ?

We have tried to change the value of sun.net.www.protocol.http.HttpURLConnection.userAgent by using reflection with this example , but it doesn't work, we're facing an IllegalAccessException .

We cannot neither set the User-Agent in the JNLP file as it is not possible to determine client information (user language + platform).

You can only set system properties from the JNLP file, not the started application. See http://docs.oracle.com/javase/1.5.0/docs/guide/javaws/developersguide/syntax.html for instructions on how to do this.

Unfortunately it appears that the data you are interested in is not available at that time, so this will most likely not end up as you need.

You may be able to use some of the newer proxying capabilities to get hold of the connection depending on your application. http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html .

An extreme solution could be to carry your own http proxy inside your application and then tell your application to use that, the proxy code then as the only one knows how to get out, with your added header fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM