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

当前文章收录状态:
查询中...
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请求登录了才能访问的页面:

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%25253A%25252F%25252Fi.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());
    }
© 版权声明
THE END
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=270198dipw4ko
点赞14赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容