java - 使用 Okhttp formdata 登录网站
问题描述
我有一些使用纯 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,但它似乎在工作
我不知道我还能做错什么
解决方案
推荐阅读
- sql - SQL - 如何在 where 子句条件中添加计数
- android - 使用服务时Android应用关闭时如何从服务器获取数据并显示在通知中
- javascript - 我在 html 页面中的函数没有执行
- java - 如何使用 Ant 扩展 xml 文件中的非实体引用
- microsoft-graph-api - 如何发送嵌套附件?
- android - 如何在具有两个不同视图的异构回收视图中实现文件管理器(搜索)?
- python - Python:在字符串列表中检查字符串的方法,但仅在列表中的特定位置。就像检查“a”是否在第一个插槽中
- openlayers - 为什么示例不起作用?(与进口的斗争)
- c# - C# 通用表
- python - Python unicode、UCS4 构建或 UCS2 构建