【问题标题】:Share cookies between React Native Activity and Native Android Activity using Cookie Jar使用 Cookie Jar 在 React Native Activity 和 Native Android Activity 之间共享 cookie
【发布时间】:2017-02-13 03:51:24
【问题描述】:

我正在构建一个应用程序,该应用程序需要我使用原生 Android 活动和 React Native Android 活动。我向服务器发出请求以授权自己并使用 cookie 在我的 Android 活动中获取资源。我也想在我的 React Native Activity 中使用这些相同的 cookie。

在我的 Android 活动中,我使用 OkHTTP3 客户端发出请求并处理我的 cookie。这个库有一个有用的 CookieJar 类,它为我处理存储和发送 cookie。

在我的 React Native 活动中,我使用 fetch 发出请求,这些请求在后台使用 OkHTTP。有没有办法让我通过 Javascript 代码访问我的持久 Cookie Jar,这样我就可以在两个活动之间无缝持久化 cookie

我知道一个解决方案是使用桥接并制作我自己的 Java 类,以 Javascript 可访问的方式包装我的 AuthClient,但这个解决方案并不是我真正想要的。

这个类是Android Activity

public class AndroidActivity extends AppCompatActivity {

    private Button switchToReactButton;
    private Button loginButton;
    private Button getFeedButton;
    private EditText usernameEditText;
    private EditText passwordEditText;
    private OkHttpClient mOkHttpClient;
    private AuthClient mHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_native);
        switchToReactButton = (Button) findViewById(R.id.switchToReactButton);
        getFeedButton = (Button) findViewById(R.id.getFeedButton);
        usernameEditText = (EditText) findViewById(R.id.usernameEditText);
        passwordEditText = (EditText) findViewById(R.id.passwordEditText);
        loginButton = (Button) findViewById(R.id.loginButton);

        mOkHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new LoggingInterceptor())
                .cookieJar(new MyCookieManager())
                .build();
        mHttpClient = new AuthClient(mOkHttpClient);

        switchToReactButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AndroidActivity.this, ReactNativeActivity.class);
                startActivity(intent);
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();

                try {
                    mHttpClient.doAuth(username, password);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        getFeedButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mHttpClient.getFeed();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

这个类是AuthClient

public class AuthClient {

    private String username;
    private String password;
    OkHttpClient client;

    public AuthClient(OkHttpClient client)
    {
        this.client = client;
    }

    public void doAuth(String username, String password) throws Exception {
        this.username = username;
        this.password = password;
        Object TAG_CALL = new Object();
        Request getRequest = new Request.Builder()
                .url("https://mywebsite.com/suite/")
                .tag(TAG_CALL)
                .build();
        getAuthCookies(getRequest);
    }

    private void getAuthCookies(Request request) {
        client.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                postAuth();
            }
        });
    }

    private void postAuth() throws IOException {
        MediaType JSON = MediaType.parse("application/x-www-form-urlencoded");

        HttpUrl url = HttpUrl.parse("https://mywebsite.com/suite/auth");
        List<Cookie> cookies = client.cookieJar().loadForRequest(url);

        String json = "un="+username+"&pw="+password+"&_spring_security_remember_me=on&X-TOKEN="
                + cookies.get(1).value();

        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(JSON, json))
                .addHeader("Accept", "text/html")
                .addHeader("Accept-Language", "en_US")
                .addHeader("Cookie2", "$Version=1")
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    }

    public void getFeed() {

        HttpUrl url = HttpUrl.parse("https://mywebsite.com/suite/api/feed/");
        List<Cookie> cookies = client.cookieJar().loadForRequest(url);

        Request getRequest = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/xml, text/xml, text/html, application/*+xml, application/atom+xml")
                .addHeader("Accept-Language", "en_US")
                .addHeader("Cookie2", "$Version=1")
                .build();

        client.newCall(getRequest).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                Log.i("NATIVE", "feed: " + response.body());
            }
        });
    }
}

【问题讨论】:

    标签: javascript android cookies react-native okhttp3


    【解决方案1】:

    解决方案是简单地使用由 React Native NetworkingModule 创建的 OkHTTP 客户端。此客户端通过应用程序持续存在并拥有自己的 CookieJar。在 javascript 中使用 fetch 使用此客户端,并且能够获取和设置 cookie。如果我们简单地使用同一个客户端实例在 Native Java 代码中发出请求,一切都会完美运行。

    mHttpClient = new AuthClient(OkHttpClientProvider.getOkHttpClient());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2021-04-06
      • 2018-05-02
      相关资源
      最近更新 更多