I tried to set the User Agent for http request like this:
public BufferedReader readURL(String url){
URL urlcon;
BufferedReader in = null;
try {
urlcon = new URL(url);
connection = (HttpURLConnection)urlcon.openConnection();
System.setProperty("http.agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)");
System.out.println(connection.getHeaderField("User-Agent"));
connection.connect();
in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String header = connection.getHeaderField(0);
System.out.println(header);
System.out.println("---Start of headers---");
int i = 1;
while ((header = connection.getHeaderField(i)) != null) {
String key = connection.getHeaderFieldKey(i);
System.out.println(((key==null) ? "" : key + ": ") + header);
i++;
}
System.out.println(connection.getHeaderField("http.agent"));
System.out.println("---End of headers---");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return in;
}
And what i got was User-Agent null:
null
HTTP/1.0 200 OK
---Start of headers---
Server: Apache
Cache-Control: max-age=10
Expires: Sun, 07 Aug 2011 16:09:26 GMT
Vary: Accept-Encoding
Content-Type: text/html
Content-Length: 163582
Date: Sun, 07 Aug 2011 16:09:20 GMT
X-Varnish: 889692780 889684459
Age: 4
Connection: keep-alive
X-Bip: 889692780 70 148
Via: 1.1 CachOS
null
---End of headers---
Why can't I set the User-Agent ?