HttpClient加JSON保持登陆状态浏览知乎

本文介绍如何使用Java保持知乎网站的登录状态,通过导入并利用Chrome的cookie信息,并将其转换为JSON格式,进而设置HTTP请求头实现状态保持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

保持着cookie,就意味着你保持着自己的登陆状态,这里省略了获取cookie的状态,我是用Chrome中的EditThisCooike
这里写图片描述

把其中的cookie信息导入到json文件中
这里写图片描述

像这样,然后提取cookie用json-lib,有个较坑的bug就是依赖包,我放张图,给大家看我的json包,有两个包不能用最新的,不然无法运行。这里写图片描述

用chrome查看request的头部信息,来设置信息
这里写图片描述
最后贴上代码

public class zhihu {
    public static void main(String[] args) {
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();//设置浏览器模式
        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

        try {
            HttpGet get = new HttpGet("https://www.zhihu.com/");
            //如果把页面打印到控制台上,会有姓名,和进入主页等,如果不保持状态,会到输入账号密码的页面
//根据chrome设置的头部
            get.setHeader("Accept-Language","en-US,en;q=0.8");
            get.setHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36");



            //json分析
            String json  = ReadFile("/Users/wang/Documents/cookie.json");
            JSONArray jsonArray = JSONArray.fromObject(json);
            int size = jsonArray.size();
            StringBuilder cookie = new StringBuilder();
            for (int i=0;i<size;i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                //设置cookie
                cookie.append(jsonObject.get("name"));
                cookie.append("=");
                cookie.append(jsonObject.get("value"));
                cookie.append("; ");

            }
            System.out.println(cookie);

            get.setHeader("Cookie",cookie.toString());
            HttpResponse response = client.execute(get);
            HttpEntity httpEntity = response.getEntity();

            System.out.println(EntityUtils.toString(httpEntity));
            System.out.println(response.getStatusLine().getReasonPhrase());





        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //读取json文件的内容
    public static String ReadFile(String Path) {
        String laststr = "";
        File file = new File(Path);
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                laststr = laststr + str;
            }
            bufferedReader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return laststr;
    }
}

进入成功结果
这里写图片描述
这里写图片描述

当我注释掉设置cookie的语句时再发送请求得道到
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值