java - 对在 HttpClient 中创建 cookie 的不同方法感到困惑

标签 java cookies struts2 apache-commons-httpclient

在 HttpClient 中有多种创建 cookie 的方法,我不知道哪种方法最好。 我需要创建、检索和修改 cookie。

例如,我可以使用以下代码查看 cookie 列表并修改它们,但如何创建它们?

这是检索它们的正确方法吗?我需要它们在所有类(class)中都可以访问。

  • 此外,我发现的其他方法通常需要 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.

最佳答案

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

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

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

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

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

你的第二个例子,虽然,跨越 execute 方法,因为你在你的标签中暗示 struts2,也许包含它的类是一个 struts2 Action.

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

第一种方法是获取 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;
    }

}

可以使用 CookieProviderInterceptor 获得另一种方法(没有 HttpServletResponse) .

struts.xml中启用它

<action ... >
  <interceptor-ref name="defaultStack"/>
  <interceptor-ref name="cookieProvider"/>
  ...
</action>

然后将 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";
    }

}

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

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

  • 在您的Action 中实现ServletRequestAware 并从HttpServletRequest 中读取cookie>
  • 引入一个CookieInterceptor 并在您的Action 中实现CookiesAware,方法setCookieMap 允许读取cookie。

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

关于java - 对在 HttpClient 中创建 cookie 的不同方法感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17779656/

相关文章:

internet-explorer - 关闭浏览器时用户在 IE 中注销

ruby-on-rails - authlogic如何保存 session ?

java - Hibernate 和 Apache Struts2 - 事务未成功启动

java - 想要从struts2网页动态执行java类(包含main)

java.lang.ClassNotFoundException : _BuildScript_

java - fragment 未按预期显示/隐藏

java - AlertDialog如何处理对话框 View 之外的点击

java - 关于 JVM 内部的 -classpath 初始化

javascript - ie9 ajax跨域withCredentials不发送cookie

java - Struts2 验证条件