Saad Attieh
Saad Attieh

Reputation: 1486

real world user agents - what are they? How to set them? - Java

I am using this line to open a stream in my java program but I think I am being blocked because of my real world user agent.

private InputStream is = new URL(a).openStream();  

Where a is a String containing the url.

What is the simplest way I can set the user agent? I have only just learned about them so any further info would be greatly appreciated. For example: I want to set it to Mozilla/5.0. Do I have to add any further information? If so what should be included and how? Also, is this strictly allowed as in should I be concerned about any legal issues with regards to setting a user agent? Apologies if that question does not make sense it's just because I no very little about user agents (basically that programs send them) and I am not sure if you have to b registered or something - I've seen that Safari on my Mac adds: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17

Thanks

Ps I have read a similar question on this but I did not understand much from the answer - I am a java beginner and have only just begun trying to open streams to files and urls.

Upvotes: 3

Views: 1476

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340973

What is the simplest way I can set the user agent?

URLConnection urlConnection = new URL(a).openConnection();
urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0");
InputStream is = urlConnection.getInputStream();

I want to set it to Mozilla/5.0. Do I have to add any further information?

You can set it to whatever you want. It's actually a good idea to identify your application, otherwise all Java programs simply send:

User-Agent: Java/1.7.0_11

Also, is this strictly allowed as in should I be concerned about any legal issues with regards to setting a user agent?

Nope, you are free to use any user agent as you want. Moreover it's not illegal to fake user agents. But if a website makes any decisions (especially regarding security) based on User-Agent, it's so bad as it's almost illegal ;-) (see: Java - Not getting html code from a URL).

Upvotes: 5

Related Questions