java通过post登录后获得1|#|4|15|pageRedirect||%2fDefault.aspx|再怎么获取cookie
时间: 2023-12-26 10:05:20 浏览: 25
以下是Java通过POST登录后获取cookie的代码示例:
```java
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象,设置url访问地址
HttpPost httpPost = new HttpPost("https://www.google.com/accounts/CheckCookie?chtml=LoginDoneHtml");
// 设置请求头信息
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader("Referer", "https://www.google.com/");
// 创建参数列表
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("username", "rose"));
list.add(new BasicNameValuePair("password", "123"));
// 设置请求参数
HttpEntity entity = new UrlEncodedFormEntity(list);
httpPost.setEntity(entity);
// 执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);
// 获取cookie
Header[] headers = response.getHeaders("Set-Cookie");
for (Header header : headers) {
String cookie = header.getValue();
if (cookie.contains("SID")) {
System.out.println("获取到的cookie为:" + cookie);
break;
}
}
// 关闭资源
response.close();
httpClient.close();
```