只是澄清:setRequestProperty工作得很好!至少在Java 1.6.30中。
我聽我的機器上使用netcat的(一個端口監聽):
$ nc -l -p 8080
它只是監聽的端口,讓你看到它獲取要求,像原始HTTP報頭什麼。
,得到了下面的HTTP報頭,而不調用setRequestProperty:
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
,並與調用setRequestProperty:
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
正如你所看到的用戶代理進行正確設置。
完整的示例:
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());
}
}
你怎麼知道這是由此產生的用戶代理?你在哪裏看到它? – skaffman 2010-03-27 15:02:06
通過PHP獲取並在Java抓取的頁面上顯示它。 – DiglettPotato 2010-03-27 15:44:09