首页 > 解决方案 > 使用 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,但它似乎在工作

我不知道我还能做错什么

标签: javajsoupokhttp3

解决方案


推荐阅读