如何从响应改造中检索cookie,okhttp?

时间:2018-01-04 07:20:13

标签: android cookies retrofit2 session-cookies okhttp3

我试图通过在APP关闭的情况下将cookie值设置为新的API调用来从API响应中检索Cookie值以维护后端会话:

来自 PostMan RestClient 的API调用响应: enter image description here

RetrofitClient.java

public static Retrofit getClient() {

    if (checkClient()) {
        return getRetrofit();
    }

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    CookieHandler cookieHandler = new CookieManager();

    okhttp3.OkHttpClient client = new okhttp3.OkHttpClient.Builder().addNetworkInterceptor(interceptor)
            .cookieJar(new JavaNetCookieJar(cookieHandler))
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(client)
            .build();
    return retrofit;
}

API致电

private void userLogin(String username, String password) {
    Retrofit retrofit = RetrofitClient.getClient();

    final LoginServices loginServices = retrofit.create(LoginServices.class);
    Call<LoginResponse> call = loginServices.userLogin(username, password);

    call.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            Log.d("Response code:", "===========" + response.code());

            Log.d("==Cookie==1===", "==="+response.raw().request().headers().get("Cookie"));
            Log.d("==Cookie==2==", "==="+response.headers().get("Cookie"));
            Log.d("==Content-Type====", "==="+response.headers().get("Content-Type"));

        }

        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {
            Log.e("TAG", "=======onFailure: " + t.toString());
            t.printStackTrace();
            // Log error here since request failed
        }
    });
}

logcat的:

Response code:: ===========200
==Cookie==1===: ===null
==Cookie==1===: ===null
==Content-Type====: ===application/json

我也尝试了其他各种方法,但他们并没有为我工作。请帮助!

3 个答案:

答案 0 :(得分:9)

List<String> Cookielist = response.headers().values("Set-Cookie");
String jsessionid = (Cookielist .get(0).split(";"))[0];

这对我有用,不是完美的解决方案,但它有效

答案 1 :(得分:4)

标题名称是&#34; Set-Cookie&#34;不是&#34; Cookie&#34;顺便说一句

你采取的方法不合适。如果要保存Cookie,可以创建一个拦截器并保存Cookie,并在以后随时使用。

这里你需要做的,首先创建一个拦截器

public class ReceivedCookiesInterceptor implements Interceptor {

PreferencesHelper preferencesHelper;

public ReceivedCookiesInterceptor(Context context) {
    FineractApplication.get(context).getComponent().inject(this);
    preferencesHelper = PreferencesHelper(context)
}

@Override
public Response intercept(Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());

    if (!originalResponse.headers("Set-Cookie").isEmpty()) {
        HashSet<String> cookies = new HashSet<>();
        for (String header : originalResponse.headers("Set-Cookie")) {
            cookies.add(header);
        }
        // Save the cookies (I saved in SharedPrefrence), you save whereever you want to save
        preferencesHelper.putStringSet(PreferenceKey.PREF_KEY_COOKIES, cookies);
    }
    return originalResponse;
  }
}

这里我们保存您收到的所有Cookie。

现在你有饼干,是时候使用了它。

只要您想使用它,只需获取之前保存的Cookie

即可
 HashSet<String> cookies = (HashSet<String>) preferencesHelper.getStringSet(
                        PreferenceKey.PREF_KEY_COOKIES);
        if (cookies != null) {
            for (String cookie: cookies) {  
                // Use this cookie whereever you wanna use.               
                Log.d("Cookie", cookie);                 
            }
        }

祝你好运

答案 2 :(得分:0)

尝试response.headers()。get(&#34; Set-Cookie&#34;))