通过restTemplate模拟浏览器登录并携带cookie请求接口
查看网页cookie
  • 通过网页调试,可以发现cookie在登录接口返回的response header里面
    在这里插入图片描述
  • 知道cookie的返回方式和位置之后,我们就可以通过代码模拟浏览器登录并获取cookie
通过restTemplate登录并获取cookie
    public void testLogin() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 设置请求boby
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("username", "用户名");
        body.add("password", "密码");
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, headers);

        String url = "登录的url";
        ResponseEntity<String> resp = restTemplate.postForEntity(url, entity, String.class);
        List<String> cookie = resp.getHeaders().get("Set-Cookie");
        log.info("模拟浏览器登录,获取Cookie为:{}", cookie);
    }
  • 执行代码得到结果为:
2022/01/12 09:45:12.375 INFO  c.k.k.s.s.m.HaoParkSyncServiceTest - 模拟浏览器登录,获取Cookie为:[s=cFdLJisdNxIvVjgxFnFHGk9BFnEWNzt1Gzk8BwBfeGpBeFl7CmB0FhV0bH0Ofj9kRFkXSV5aeBF4Xg;Path=/;Expires=Fri, 21-Nov-2031 01:40:37 GMT]
通过上一步获取的cookie,模拟浏览器调用其他接口
    public void test() {
        HttpHeaders headers = new HttpHeaders();
        List<String> cookies = new ArrayList<>();
        // 登录获取Cookie 这里是直接给Cookie,可使用下方的login方法拿到Cookie给入
        // 把上一步获取的cookie,在请求header里面传入
cookies.add("s=cFdLJisdNxIvVjgxFnFHGk9BFnEWNzt1Gzk8BwBfeGpBeFl7CmB0FhV0bH0Ofj9kRFkXSV5aeBF4Xg;Path=/;Expires=Fri, 21-Nov-2031 01:12:48 GMT");
        // 将cookie存入头部
        headers.put(HttpHeaders.COOKIE, cookies);
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> paramMap=new HashMap<>();
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(paramMap, headers);
        String url = "接口路径";
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        log.info("模拟浏览器请求接口,返回数据:{}", response.getBody());
    }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐