How do I fake an specific browser client when using Java's Net library?

蹲街弑〆低调 提交于 2019-12-11 01:46:50

问题


A small program of mine just broke because, it seems, the site I was programmatically browsing now assumes a Java request comes from a mobile phone, and the link I was looking for is not on their mobile page.

So I want to fake an Internet Explorer access. How do I do that with java.net?


回答1:


IIRC, set "http.agent" system property through System, -D on the command line, in your JNLP file or elsewhere.




回答2:


Assuming you're using java.net.URLConnection, then call setRequestProperty(String,String) to set the request header to a value that IE would use. For example, to fake IE6:

URL url = new URL("http://google.com");
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 1.2.30703)");

and then use the connection object as before.

But java.net is horrible. Use Apache Commons HttpClient instead, it's much nicer.

Even better, use a framework designed for navigating websites, like HtmlUnit




回答3:


You need to set the User-Agent header in the HTTP request to a value used by Internet Explorer.

I recommend using the Jakarta HttpClient library to make the request as it provides a higher level API for manipulating the request.



来源:https://stackoverflow.com/questions/1144073/how-do-i-fake-an-specific-browser-client-when-using-javas-net-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!