Cookie概念:Cookie服务器发送给浏览器的一小段文本信息
Java后台获取Cookie正常操作:
Cookie[] cookies = request.getCookies();
if(cookies != null && cookies.length > 0){
for (Cookie cookie : cookies){
return cookie.getName() + " " + cookie.getValue();
}
}
但是,只能获取自己域里的cookie,即localhost域下的Cookie,无法获取其他域里的Cookie。
获取其他域里的Cookie:
1.通过浏览器开发者模式查看相应域里的Cookie,通过Cookie获取值;
2.通过HttpClient向服务器发送登录请求,获取相应结果里的Set-Cookie,下次向服务器发送请求时带上Cookie;
3.通过WebMagic框架selenium模拟浏览器实现登陆
方法二案例:
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* @auther mxh
* @time 2019/5/20 13:48
*/
public class ZhiHuTest {
public static void main(String[] args) throws java.text.ParseException {
String name = "******@qq.com"; //
String password = "******"; //
// 全局请求设置
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
// 创建cookie store的本地实例
CookieStore cookieStore = new BasicCookieStore();
// 创建HttpClient上下文
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
// 创建一个HttpClient
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
.setDefaultCookieStore(cookieStore).build();
CloseableHttpResponse res = null;
// 创建本地的HTTP内容
try {
try {
// 创建一个get请求用来获取必要的Cookie,如_xsrf信息
HttpGet get = new HttpGet("http://www.zhihu.com/");
res = httpClient.execute(get, context);
// 获取常用Cookie,包括_xsrf信息
System.out.println("访问知乎首页后的获取的常规Cookie:===============");
for (Cookie c : cookieStore.getCookies()) {
System.out.println(c.getName() + ": " + c.getValue());
}
res.close();
// 构造post数据
List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
valuePairs.add(new BasicNameValuePair("email", name));
valuePairs.add(new BasicNameValuePair("password", password));
valuePairs.add(new BasicNameValuePair("remember_me", "true"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
entity.setContentType("application/x-www-form-urlencoded");
// 创建一个post请求
HttpPost post = new HttpPost("https://www.zhihu.com/login/email");
// 注入post数据
post.setEntity(entity);
res = httpClient.execute(post, context);
// 打印响应信息,查看是否登陆是否成功
System.out.println("打印响应信息===========");
System.out.println(res.toString());
res.close();
System.out.println("登陆成功后,新的Cookie:===============");
for (Cookie c : context.getCookieStore().getCookies()) {
System.out.println(c.getName() + ": " + c.getValue());
}
// 构造一个新的get请求,用来测试登录是否成功
HttpGet newGet = new HttpGet("https://www.zhihu.com/question/293207596/answer/684673400");
res = httpClient.execute(newGet, context);
String content = EntityUtils.toString(res.getEntity());
System.out.println("登陆成功后访问的页面===============");
System.out.println(content);
res.close();
} finally {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码,只要网站登陆登录过程不是太繁琐,如需要验证则不太实用
方案三实现代码:
// 自动登陆方法
public void login() {
//注册chrome
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://login.jiayuan.com/?refrer=http://www.jiayuan.com&host=0");// 打开网址
// 防止页面未能及时加载出来而设置一段时间延迟
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 设置用户名密码
driver.findElement(By.id("login_email")).sendKeys("15735400536"); // 用户名
driver.findElement(By.id("login_password")).sendKeys("mxh970923"); // 密码
// 模拟点击 //form[@id='form-group-login']/button
driver.findElement(By.xpath("//*[@id=\"login_btn\"]"))
.click(); // xpath语言:id为form-group-login的form下的button
// 防止页面未能及时加载出来而设置一段时间延迟
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 获取cookie信息
cookies = driver.manage().getCookies();
driver.close();
}