My problem is that I want to use Java t开发者_StackOverflow社区o implement an application which sends an HTTP GET request to some website. However, the target website needs one cookie to be set:
Country=US
If this cookie is null it returns bad indications. My question is how I can set the cookie value before I use openConnection()
?
You can use URLConnection
and add a Cookie
header:
http://www.hccp.org/java-net-cookie-how-to.html
URL myUrl = new URL("http://www.yourserver.com/path");
URLConnection urlConn = myUrl.openConnection();
urlConn.setRequestProperty("Cookie", "Country=US");
urlConn.connect();
You can place the cookie your self by adding a header, or use a higher level HTTP library like Apache's HttpClient which API includes cookies handling features.
精彩评论