代码语言: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());
}