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

保持着cookie,就意味着你保持着自己的登陆状态,这里省略了获取cookie的状态,我是用Chrome中的EditThisCooike
HttpClient加JSON保持登陆状态浏览知乎_第1张图片

把其中的cookie信息导入到json文件中
HttpClient加JSON保持登陆状态浏览知乎_第2张图片

像这样,然后提取cookie用json-lib,有个较坑的bug就是依赖包,我放张图,给大家看我的json包,有两个包不能用最新的,不然无法运行。HttpClient加JSON保持登陆状态浏览知乎_第3张图片

用chrome查看request的头部信息,来设置信息
HttpClient加JSON保持登陆状态浏览知乎_第4张图片
最后贴上代码

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//设置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;
    }
}

进入成功结果
这里写图片描述
HttpClient加JSON保持登陆状态浏览知乎_第5张图片

当我注释掉设置cookie的语句时再发送请求得道到
HttpClient加JSON保持登陆状态浏览知乎_第6张图片

你可能感兴趣的:(java)