Java后台获取Cookie

Java后台获取Cookie

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 valuePairs = new LinkedList();

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

}

相关推荐

魔兽世界最拉风外套的获取方式,需要爆肝20个小时
365bet提款条件

魔兽世界最拉风外套的获取方式,需要爆肝20个小时

🗓️ 07-04 👁️ 5023
宜家橱柜怎么样?质量好不好?
趣投必发365

宜家橱柜怎么样?质量好不好?

🗓️ 01-20 👁️ 8155
行车记录仪的电源线怎么接?
365bet提款条件

行车记录仪的电源线怎么接?

🗓️ 01-14 👁️ 9565
魔兽世界怀旧服:火猫幻化上架,外观与正式服有区别,玩家测试提升10%伤害?
跑男成员一季能挣多少钱?李晨够一环买套房,而他却不够别人零头
娱乐圈清流!陈赫把鹿晗宠成“小孩”,这份神仙友谊太好嗑。
淘宝零食店铺有哪些
趣投必发365

淘宝零食店铺有哪些

🗓️ 07-31 👁️ 9595
北欧女神全关键物品一览 北欧女神蕾娜斯神器一览
365bet提款条件

北欧女神全关键物品一览 北欧女神蕾娜斯神器一览

🗓️ 08-09 👁️ 2800
哤杂是什么意思
趣投必发365

哤杂是什么意思

🗓️ 08-16 👁️ 6725
卡盟刷永久钻真的存在吗?其背后的风险与真相是什么?
微信账户注销后再申请的等待与注意事项
365bet提款条件

微信账户注销后再申请的等待与注意事项

🗓️ 09-08 👁️ 5949
貂蝉生肖之谜:她究竟属于哪个生肖?
365bet提款条件

貂蝉生肖之谜:她究竟属于哪个生肖?

🗓️ 08-04 👁️ 2608