Home >Java >javaTutorial >How to Set the User Agent of a Java URLConnection Without Java Additions?

How to Set the User Agent of a Java URLConnection Without Java Additions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 20:59:12544browse

How to Set the User Agent of a Java URLConnection Without Java Additions?

Setting the User Agent of a Java URLConnection Without Java Addition

In Java, setting the User-Agent property of a URLConnection typically adds "Java/version" to the end of the agent string specified. To achieve a pure user-specified User-Agent, the following steps are necessary:

Java 1.6.30 and Later

In Java versions 1.6.30 and later, setRequestProperty("User-Agent", "user-agent-string") sets the agent without Java addition. This can be confirmed by listening for incoming requests with a port listener like netcat:

$ nc -l -p 8080

Without setRequestProperty, the headers will look like this:

GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

With setRequestProperty, the User-Agent will be correctly set:

GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

Full Example:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class TestUrlOpener {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/foobar");
        URLConnection hc = url.openConnection();
        hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        System.out.println(hc.getContentType());
    }

}

The above is the detailed content of How to Set the User Agent of a Java URLConnection Without Java Additions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn