java如何通过使用HttpClients发送get请求并且获取cookies代码
时间: 2023-03-29 14:04:10 浏览: 89
根据http获取cookie内容代码
您好,以下是Java使用HttpClients发送get请求并获取cookies的代码示例:
```
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import java.util.List;
public class HttpGetWithCookies {
public static void main(String[] args) throws Exception {
// 创建CookieStore实例
CookieStore cookieStore = new BasicCookieStore();
// 创建HttpClient实例,并将CookieStore设置到HttpClient中
HttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
// 创建HttpGet请求实例
HttpGet httpGet = new HttpGet("http://www.example.com");
// 执行HttpGet请求,并获取响应
httpClient.execute(httpGet);
// 获取CookieStore中的所有Cookie
List<org.apache.http.cookie.Cookie> cookies = cookieStore.getCookies();
// 输出所有Cookie的名称和值
for (org.apache.http.cookie.Cookie cookie : cookies) {
System.out.println(cookie.getName() + ": " + cookie.getValue());
}
}
}
```
希望对您有所帮助。
阅读全文