怎么给http请求添加cookie

Setting a cookie value in a request:

1.
Values must be set prior to calling the connect method:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
2.
Create a cookie string:
String myCookie = "userId=igbrown";
3.
Add the cookie to a request:
Using the setRequestProperty(String name, String value); method, we will add a property named "Cookie", passing the cookie string created in the previous step as the property value.

urlConn.setRequestProperty("Cookie", myCookie);
4.
Send the cookie to the server:
To send the cookie, simply call connect() on the URLConnection for which we have added the cookie property:

urlConn.connect()


Setting a multiple cookie values in a request:


1.
Perform the same steps as the above item (Setting a a cookie value in a request), replacing the single valued cookie string with something like the following:
String myCookies = "userId=igbrown; sessionId=SID77689211949; isAuthenticated=true";
This string contains three cookies (userId, sessionId, and isAuthenticated). Separate cookie name/value pairs with "; " (semicolon and whitespace).

Note that you cannot set multiple request properties using the same name, so trying to call the setRequestProperty("Cookie" , someCookieValue) method will just overwrite any previously set value.
原文摘自:http://www.hccp.org/java-net-cookie-how-to.html

你可能感兴趣的:(java)