重用Jsoup连接 [英] reuse the Jsoup connection

查看:92
本文介绍了重用Jsoup连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢用Jsoup解析html,但是它们的连接有问题,我需要将请求发送到同一网站,但查询参数不同,例如"id = XXX",请求是这样的:

i like Jsoup for parsing html, but has problem with their connection, i need to send request to the same website but different query parameter, say "id=XXX", the request is like this:

http://website/?id=XXX

我不想为每个id创建一个新的连接,而是为所有id请求保留一个连接,这是我的代码:

i dont want to create a new connection for each id, instead i keep one connection for all the id request, here is my code:

Connection conn = null;

..
if (_conn == null) {
 _conn = Jsoup.connect("http://website/";
}
doc = _conn.data("id", id).get()
..

但是它似乎只在第一次工作,然后每次我的代码运行时都重复相同的请求,在这种情况下,即使我其他时候传递了不同的ID,我也只能查询第一个ID.我该如何解决?

but it seems it only works for the first time, and then just repeat the same request everytime my code run, in that case i can only query the first id even though i pass different id for other time. how can i solve this?

推荐答案

我已经通过为每个请求更改_conn.url();来实现某种重用 因此,在您的情况下,类似

I've managed to achieve some kind of reuse by changing _conn.url(); for every request so in your case that would be something like

String siteUrl = "http://website/";
Connection _conn = Jsoup.connect(siteUrl);
int[] ids = {1,2,3};
for (int i : ids) {
    _conn.url(siteUrl + "?id=" + i);
    Document doc = _conn.get();
}

在我看来,这比更改_conn.request().data()优雅得多,但这似乎是唯一的方法.

This is much less elegant than changing _conn.request().data() in my opinion, but it appears that this is the only way.

希望有帮助.

这篇关于重用Jsoup连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆