Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reuse the Jsoup connection

Tags:

jsoup

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

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()
..

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?

like image 786
user468587 Avatar asked Nov 03 '22 09:11

user468587


1 Answers

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();
}

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

Hope it helps.

like image 103
Alex Ackerman Avatar answered Jan 04 '23 13:01

Alex Ackerman