对单个站点的多个GET请求(规范)(java)

时间:2011-08-01 10:38:45

标签: java cookies get

您好我正在尝试向单个连接发出2个GET请求。即

HttpGet get1 = new HttpGet("http://www.google.com/search?q=HelloWorld");
HttpGet get2 = new HttpGet("http://www.google.com/search?q=SecondSearch");

HttpResponse response = null;

response = client.execute(get1);
response = client.execute(get2);

我想从第二次执行得到身体。显然这失败了,因为它说你必须先释放连接。我需要维护确切的会话 - 例如,如果我导航到第一步登录的站点,我需要导航到具有相同cookie的任何后续页面。

我做错了可能非常简单!

1 个答案:

答案 0 :(得分:2)

您需要使用CookieStore

CookieStore cookieStore = new BasicCookieStore();

DefaultHttpClient client1 = new DefaultHttpClient();
client1.setCookieStore(cookieStore);
HttpGet httpGet1 = new HttpGet("...");
HttpResponse response1 = client1.execute(httpGet1);

DefaultHttpClient client2 = new DefaultHttpClient();
client2.setCookieStore(cookieStore);
HttpGet httpGet2 = new HttpGet("...");
HttpResponse response2 = client2.execute(httpGet2);

在上面的代码中,client2都将重新使用来自client1请求的cookie。