How do you prevent Retrofit from automatically following a 302

前端 未结 5 1373
忘了有多久
忘了有多久 2021-02-18 23:43

I have an authentication call that i\'m trying to make using Retrofit on Android. The call returns a 302 to either a success or failure page. The original 302 response brings ba

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-19 00:31

    I was in a similar situation to yours. Basically all we need is to capture the "Set-Cookie" header that your server returns before redirecting. This is how I handled it using OkHTTP:

    final OkHttpClient client = new OkHttpClient();
    CookieHandler handler = client.getCookieHandler();
    CookieManager manager = new CookieManager();
    handler.setDefault(manager);
    
    //boilerplate:
    RequestBody formData = new FormEncodingBuilder()
            .add("req_username", username)
            .add("req_password", password).build();
    Request request = new Request.Builder().url(LOGIN_URL).post(formData).build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    
    // print our cookies:
    List  cookies = manager.getCookieStore().getCookies();
    for(HttpCookie cookie : cookies) {
        Log.v(TAG, cookie.getName() + "=" + cookie.getValue());
    }
    

提交回复
热议问题