混淆了在HttpClient中创建cookie的不同方法

Tim*_*man 6 java cookies struts2 apache-commons-httpclient

在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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下代码创建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();
  }
Run Code Online (Sandbox Code Playgroud)

输出如下,但不会创建cookie.

SEVERE: Creating the cookie
SEVERE: cookie
Run Code Online (Sandbox Code Playgroud)

脚本

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.
Run Code Online (Sandbox Code Playgroud)

Car*_*ini 3

在第二个示例中,您正在创建一个新的客户端 cookie(即您正在模拟浏览器并将 cookie 发送到服务器)。

这意味着您需要提供所有相关信息,以便客户端可以决定是否将cookie发送到服务器。

在您的代码中,您正确设置了路径、名称和值,但缺少 域信息。

org.apache.commons.httpclient.Cookie cookie 
  = new org.apache.commons.httpclient.Cookie();
cookie.setDomain("localhost");
cookie.setPath("/");
cookie.setName("Tim");
cookie.setValue("Tim");
Run Code Online (Sandbox Code Playgroud)

如果您想要实现的是将cookie 发送到 http 服务器,则此方法有效。

不过,您的第二个示例跨越了一个execute方法,因为您在标记中暗示了 struts2 ,所以包含它的类可能应该是 struts2 Action

如果是这种情况,您想要实现的目标就是向浏览器发送一个新的 cookie

第一种方法是获取 a ,HttpServletResponse如下所示:

所以你的Action样子必须是这样的:

public class SetCookieAction 
    implements ServletResponseAware  // needed to access the 
                                     // HttpServletResponse
{

    HttpServletResponse servletResponse;

    public String execute() {
        // Create the cookie
        Cookie div = new Cookie("Tim", "Tim");
        div.setMaxAge(3600); // lasts one hour 
        servletResponse.addCookie(div);
        return "success";
    }


    public void setServletResponse(HttpServletResponse servletResponse) {
        this.servletResponse = servletResponse;
    }

}
Run Code Online (Sandbox Code Playgroud)

另一种方法(没有)可以使用CookieProviderInterceptorHttpServletResponse获得。

启用它struts.xml

<action ... >
  <interceptor-ref name="defaultStack"/>
  <interceptor-ref name="cookieProvider"/>
  ...
</action>
Run Code Online (Sandbox Code Playgroud)

然后实施CookieProvider为:

public class SetCookieAction 
    implements CookieProvider  // needed to provide the coookies
{

    Set<javax.servlet.http.Cookie> cookies=
            new HashSet<javax.servlet.http.Cookie>();

    public Set<javax.servlet.http.Cookie> getCookies() 
    {
            return cookies;
    }

    public String execute() {
        // Create the cookie
        javax.servlet.http.Cookie div = 
                new javax.servlet.http.Cookie("Tim", "Tim");
        div.setMaxAge(3600); // lasts one hour 
        cookies.put(cookie)
        return "success";
    }

}
Run Code Online (Sandbox Code Playgroud)

(感谢 @RomanC 指出了这个解决方案)

如果您随后需要阅读它,您有两种选择:

  • ServletRequestAware在您的中实施Action并读取 cookieHttpServletRequest
  • 引入一个并在您的 中CookieInterceptor实现,该方法允许读取 cookie。CookiesAwareActionsetCookieMap

在这里您可以找到一些相关信息: