混淆了在HttpClient中创建cookie的不同方法 [英] Confused with different methods of creating cookie in 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,我的浏览器);
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()+
,值:+ cookie.getValue()+
,IsPersistent? + cookie.isPersistent()+
,到期日期:+ cookie.getExpiryDate()+
,注释:+ 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 );
HttpClient httpclient = new HttpClient();
httpclient.getParams()。setParameter(http.useragent,我的浏览器);
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();
}
输出如下所示,
SEVERE:创建cookie
SEVERE:cookie
方案
1 )用户可以访问表单以搜索产品(example.com/Search/Products)
2)用户填写表单并将其提交到类Search
3)表单将提交到Search类
4)搜索类的方法产品返回并显示产品的描述
(example.com/Search/Products)
5)用户点击更多按钮获取关于产品的更多描述
6)请求将被发送到Product类(example.com/Product/Description?id=4)
7)用户点击添加到cookie按钮以将产品ID添加到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);
如果您想要实现的是向http服务器发送Cookie 。
你的第二个例子是一个 execute
方法,因为你在标签中暗示struts2 ,也许包含它的类意味着是一个struts2 Action
。
如果是这样,尝试实现的是向浏览器发送新的Cookie 。
第一种方法是获取 HttpServletResponse
,如:
因此,您的 Action
必须如下所示:
public class SetCookieAction
实现ServletResponseAware //需要访问
// HttpServletResponse
{
HttpServletResponse servletResponse;
public String execute(){
//创建cookie
Cookie div = new Cookie(Tim,Tim);
div.setMaxAge(3600); // lasts一小时
servletResponse.addCookie(div);
returnsuccess;
}
public void setServletResponse(HttpServletResponse servletResponse){
this.servletResponse = servletResponse;
}
}
$ c> HttpServletResponse )可以使用 CookieProviderInterceptor 。
在 struts.xml中启用它
< action ...>
< interceptor-ref name =defaultStack/>
< interceptor-ref name =cookieProvider/>
...
< / action>
然后实现 CookieProvider
as:
public class SetCookieAction
实现CookieProvider //需要提供coookies
{
设置< javax.servlet.http.Cookie> cookies =
new HashSet< javax.servlet.http.Cookie>();
public Set< javax.servlet.http.Cookie> getCookies()
{
return cookies;
}
public String execute(){
//创建cookie
javax.servlet.http.Cookie div =
new javax.servlet。 http.Cookie(Tim,Tim);
div.setMaxAge(3600); // lasts一小时
cookies.put(cookie)
returnsuccess;
}
}
- 在
Action
中实现ServletRequestAware
,并从HttpServletRequest
- 在
中引入
,方法CookieInterceptor
code> ActionsetCookieMap
允许读取Cookie。
如果您随后需要阅读它,您有两个选项:
您可以在这里找到一些相关信息:
There are different methods to create cookies in HttpClient, I am confused which one is the best. I need to create,retrieve and modify cookies.
For example , I can use the following code to see a list of cookies and modify them but how to create them ?
Is this a proper method for retrieving them? I need them to be accessible in all classes.
- In addition methods that I have found usually require httpresponse, httprequest objects to send the cookie to browser, but how about if I do not want to use them?
Code
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();
}
}
}
AND I've tried to create a cookie using following code but it does not
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();
}
Output is as following but no cookie will be created.
SEVERE: Creating the cookie
SEVERE: cookie
Scenario
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.
In the second example, you are creating a new client-side cookie (i.e. you are impersonating a browser and are sending the cookie to the server).
This means that you need to provide all the relevant information, so that the client can decide whether to send the cookie to the server or not.
In your code you correctly set the path,name and value, but the domain information is missing.
org.apache.commons.httpclient.Cookie cookie
= new org.apache.commons.httpclient.Cookie();
cookie.setDomain("localhost");
cookie.setPath("/");
cookie.setName("Tim");
cookie.setValue("Tim");
This works if what you are trying to achieve is to send a cookie to an http server.
Your second example, though, spans from an execute
method, an since you are hinting at struts2 in your tag, maybe the class containing it is meant to be a struts2 Action
.
If this is the case, what you are trying to achieve is to send a new cookie to a browser.
The first approach is to get hold of a HttpServletResponse
as in:
So your Action
must look like:
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;
}
}
Another approach (without HttpServletResponse
) could be obtained using the CookieProviderInterceptor.
Enable it in struts.xml
<action ... >
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="cookieProvider"/>
...
</action>
then implement CookieProvider
as:
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";
}
}
(credits to @RomanC for pointing out this solution)
If you subsequently need to read it you have two options:
- implement
ServletRequestAware
in yourAction
and read the cookies from theHttpServletRequest
- introduce a
CookieInterceptor
and implementCookiesAware
in yourAction
, the methodsetCookieMap
allows to read the cookies.
Here you can find some relevant info:
这篇关于混淆了在HttpClient中创建cookie的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!