在 HttpClient 中创建 cookie 有不同的方法,我很困惑哪一种是最好的。我需要创建、检索和修改 cookie。
例如,我可以使用以下代码查看 cookie 列表并修改它们,但如何创建它们?
这是检索它们的正确方法吗?我需要它们在所有课程中都可以访问。
- 另外我发现的方法通常需要httpresponse、httprequest 对象将cookie 发送到浏览器,但如果我不想使用它们怎么办?
代码
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
public class GetCookiePrintAndSetValue {
public static void main(String args[]) throws Exception {
HttpClient client = new HttpClient();
client.getParams().setParameter("http.useragent", "My Browser");
GetMethod method = new GetMethod("http://localhost:8080/");
try{
client.executeMethod(method);
Cookie[] cookies = client.getState().getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
System.err.println(
"Cookie: " + cookie.getName() +
", Value: " + cookie.getValue() +
", IsPersistent?: " + cookie.isPersistent() +
", Expiry Date: " + cookie.getExpiryDate() +
", Comment: " + cookie.getComment());
cookie.setValue("My own value");
}
client.executeMethod(method);
} catch(Exception e) {
System.err.println(e);
} finally {
method.releaseConnection();
}
}
}
并且我尝试使用以下代码创建一个 cookie,但它没有
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
....
public String execute() {
try{
System.err.println("Creating the cookie");
HttpClient httpclient = new HttpClient();
httpclient.getParams().setParameter("http.useragent", "My Browser");
GetMethod method = new GetMethod("http://localhost:8080/");
httpclient.executeMethod(method);
org.apache.commons.httpclient.Cookie cookie = new
org.apache.commons.httpclient.Cookie();
cookie.setPath("/");
cookie.setName("Tim");
cookie.setValue("Tim");
cookie.setDomain("localhost");
httpclient.getState().addCookie(cookie);
httpclient.executeMethod(method);
System.err.println("cookie");
}catch(Exception e){
e.printStackTrace();
}
输出如下,但不会创建 cookie。
SEVERE: Creating the cookie
SEVERE: cookie
设想
1)User has access to a form to search for products (example.com/Search/Products)
2)User fills up the form and submit it to class Search
3)Form will be submitted to Search class
4)Method Products of Search class returns and shows the description of product
(example.com/Search/Products)
5)User clicks on "more" button for more description about product
6)Request will be sent to Product class (example.com/Product/Description?id=4)
7)User clicks on "add to cookie" button to add the product id to the cookie
Product class is subclasse of another class. So it can not extend any more class.