我有一些使用纯Jsoup登录网站的代码。
它可以工作,但是对于整个项目,我需要Okhttp(如果仅仅是因为我对API更加熟悉)
Jsoup版本:
`
Connection.Response loginPageResp = Jsoup.connect("https://accounts.pixiv.net/login?lang=en").execute();
String postKey = loginPageResp.parse().select("input[name=post_key]").val();
Connection.Response resp = Jsoup.connect("https://accounts.pixiv.net/api/login?lang=en")
.data("pixiv_id", "XXXX")
.data("password", "xxxxxxxxxxx")
.data("captcha", "")
.data("g_recaptcha_response", "")
.data("return_to", "https://www.pixiv.net")
.data("lang", "en")
.data("post_key", postKey)
.header("Content-type", "application/x-www-form-urlencoded")
.ignoreContentType(true)
.cookie("PHPSESSID", loginPageResp.cookie("PHPSESSID"))
.method(Connection.Method.POST)
.execute();
SESSION_ID = resp.cookie("PHPSESSID");
`
OkHttp3版本:
OkHttpClient client = new OkHttpClient.Builder()
.cookieJar(new PersistentCookieJar())
.cache(new Cache(new File("html.temp", "network_cache"), 5L * 1024 * 1024))
.build();
Headers headers = new Headers.Builder()
.add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0")
.build();
Response response = client.newCall(new Request.Builder()
//.headers(headers)
.url("https://accounts.pixiv.net/login?lang=en")
.build()).execute();
String postKey = Jsoup.parse(response.body().string()).select("input[name=post_key]").val();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("pixiv_id", "XXXX")
.addFormDataPart("password", "xxxxxxxxxx")
.addFormDataPart("captcha", "")
.addFormDataPart("g_recaptcha_response", "")
.addFormDataPart("return_to", "https://www.pixiv.net")
.addFormDataPart("lang", "en")
.addFormDataPart("post_key", postKey)
.build();
Request request = new Request.Builder()
//.headers(headers)
.addHeader("Content-type", "application/x-www-form-urlencoded")
.url("https://accounts.pixiv.net/api/login?lang=en")
.post(requestBody)
.build();
client.newCall(request);
Response response1 = client.newCall(new Request.Builder().headers(headers).url("https://www.pixiv.net/bookmark_new_illust.php?p=1").build()).execute();
我对cookiejar感到怀疑,但它似乎正在起作用
我不知道我还能做错什么