使用 OkHttp 在网站上授权

Authorization on the site using OkHttp

我正在尝试访问我所在大学的网站并解析必要的信息(例如时间表等)。我检查了 reqres.in 上的工作,一切正常,但在我的网站上没有答案(调用了 onFailure)。我在 Python 中写了所有相同的内容,一切正常,网站启动了。也许我遗漏了什么,我寻求帮助。

Python 有效的代码

import requests
import re

s = requests.Session()
s.get("https://lk.sut.ru/cabinet/")

def login_bonch(login, password):
    data = {'users': login,
            'parole': password}

    r = s.post("https://lk.sut.ru/cabinet/lib/autentificationok.php", data = data)
    return r.text // Function returns 1

Android Studio 中的代码不起作用

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();

        OkHttpClient client = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("users", "username@gmail.com")
                .add("parole", "password123")
                .build();

        Request request = new Request.Builder()
                .url("https://lk.sut.ru/cabinet/lib/autentificationok.php")
                .post(formBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("SendLog", "Error");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.d("SendLog", " " + response.body().string());
            }
        });
    }

我希望现在附加正确(堆栈跟踪)

2020-06-11 03:47:46.560 2287-2315/com.foxartstd.lkbonchapp W/System.err: java.net.ProtocolException: Too many follow-up requests: 21
2020-06-11 03:47:46.560 2287-2315/com.foxartstd.lkbonchapp W/System.err:     at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:127)
2020-06-11 03:47:46.560 2287-2315/com.foxartstd.lkbonchapp W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
2020-06-11 03:47:46.560 2287-2315/com.foxartstd.lkbonchapp W/System.err:     at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
2020-06-11 03:47:46.560 2287-2315/com.foxartstd.lkbonchapp W/System.err:     at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:502)
2020-06-11 03:47:46.560 2287-2315/com.foxartstd.lkbonchapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
2020-06-11 03:47:46.561 2287-2315/com.foxartstd.lkbonchapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
2020-06-11 03:47:46.561 2287-2315/com.foxartstd.lkbonchapp W/System.err:     at java.lang.Thread.run(Thread.java:761)

我不明白如何将代码从 Python 转移到 android 应用程序。我知道也许我错过了网络会话的开始,但我不知道如何在 Java.

中实现它

答案开始来了,但我不能表现出来。添加了这些行

ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));

OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                .followRedirects(FALSE)
                .followSslRedirects(FALSE)
                .build();

我试图得到这样的答案,但我只得到 好的

 client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("SendLog", "Error");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String MyResult = response.body().string();
                Log.d("SendLog", "Ok " + MyResult);
            }

您应该使用 RequestBody.create 而不是 FormBody

RequestBody formBody = RequestBody.create("application/json; charset=utf-8", "{\"users\":\"username@gmail.com\",\"parole\":\"password123\"}")
Request request = new Request.Builder()
          .url("https://lk.sut.ru/cabinet/lib/autentificationok.php")
          .post(formBody)
          .build();

我怀疑您需要一个 CookieJar 来保持第一次调用时的会话设置

看看https://square.github.io/okhttp/4.x/okhttp/okhttp3/-cookie-jar/

https://github.com/franmontiel/PersistentCookieJar

ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                .build();

但是您的代码示例似乎并不完整。

添加这些行解决了我的问题

ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));

OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                .followRedirects(FALSE)
                .followSslRedirects(FALSE)
                .build();

正是这些截止日期帮助我们避免出错

.followRedirects(FALSE)
.followSslRedirects(FALSE)

关于答案,这些已经是网站的问题了。它 returns 1 在成功和全部的情况下,否则什么都没有。授权还没出来,主要问题已经解决