简体   繁体   English

使用HtmlUnit和Apache发送请求,同时维护cookie

[英]Sending requests using HtmlUnit and Apache while maintaining cookies

I want to write a class that uses both Apache 4.x lib and HtmlUnit. 我想编写一个同时使用Apache 4.x lib和HtmlUnit的类。 Essentially, I need the some requests to behave like a real browser, which HtmlUnit accomplishes nicely. 本质上,我需要一些请求像真实的浏览器一样运行,HtmlUnit可以很好地完成。 The downside of HtmlUnit is that it's very slow, and many of my requests don't require it. HtmlUnit的缺点是它非常慢,而且我的许多请求都不需要它。

I know that disabling css/javascript in HtmlUnit can increase processing speed but it's not enough. 我知道在HtmlUnit中禁用CSS / JavaScript可以提高处理速度,但这还不够。 I want to implement both HtmlUnit and Apache (or anything else that can do the job). 我想同时实现HtmlUnit和Apache(或其他可以完成此工作的方法)。

The only requirement I have is having the ability to define headers and pass cookies. 我唯一的要求就是能够定义标题和传递cookie。

So, is it possible to, for example: 因此,有可能例如:

  • Send a request to Website.com using Apache library and collect the cookies. 使用Apache库将请求发送到Website.com并收集cookie。
  • Send a request to Website.com/Page2 using HtmlUnit while maintaining the session and executing the javascript on page load. 使用HtmlUnit将请求发送到Website.com/Page2,同时保持会话并在页面加载时执行javascript。

So my questions are.. Can I accomplish what I'm trying to do? 所以我的问题是..我能完成我想做的事情吗? Or if I'm going about it the wrong way, is there a method to drastically speed up requests using HtmlUnit? 或者,如果我使用错误的方法,是否有一种方法可以使用HtmlUnit大大加快请求的速度? Can I share the CookieContainer between HtmlUnit's WebClient and Apache's HttpClient ? 我可以在HtmlUnit的WebClient和Apache的HttpClient之间共享CookieContainer吗?

Yes, this is possible. 是的,这是可能的。 I also do this sometimes. 我有时也会这样做。 You need to extract the cookies from htmlunit before using httpclient. 使用httpclient之前,您需要从htmlunit中提取cookie。 You do that by calling 你通过打电话来做到这一点

Set<Cookie> cookies = webClient.getCookieManager().getCookies();

You can loop through the set and extract whatever cookie you need. 您可以遍历集合并提取所需的任何cookie。 When using httpclient pass the cookie as your header parameter. 使用httpclient时,将cookie作为您的标头参数传递。 It will work. 会的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM