使用FastHttpClient自动携带Cookie进行请求

2022-06-27 12:42:30 浏览数 (1)

代码语言:javascript复制
package com.ruoyi.system.ultis;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZouYangMing
 */
public class LocalCookieJar implements CookieJar {
    List<Cookie> cookies;

    @Override
    public List<Cookie> loadForRequest(HttpUrl arg0) {
        if (cookies != null) {
            return cookies;
        }
        return new ArrayList<Cookie>();
    }

    @Override
    public void saveFromResponse(HttpUrl arg0, List<Cookie> cookies) {
        this.cookies = cookies;
    }

    public List<Cookie> getCookies(){
        return this.cookies;
    }
}

下面是带cookie请求登录了才能访问的页面:

代码语言:javascript复制
public static void main(String[] args) throws Exception {
        LocalCookieJar cookie = new LocalCookieJar();
        HttpClient client = FastHttpClient.newBuilder()
                .followRedirects(false)
                .followSslRedirects(false)
                .cookieJar(cookie)
                .build();

        String url="https://passport2.chaoxing.com/fanyalogin?fid=-1&uname=XXXX&password=XXXX=&refer=https%253A%252F%252Fi.chaoxing.com&t=true&forbidotherlogin=0&validate=";
        client.post().
                url(url).
                build().
                execute();

        System.out.println(cookie.getCookies());

        System.out.println(client.get().url("https://mooc1-2.chaoxing.com/visit/courses/study?isAjax=true").build().execute().string());
    }

0 人点赞