嘿,我需要一些帮助" okhttp"。我想存储我从请求中获得的cookie,以便稍后在应用程序中重用它。我遇到了这个例子,但问题是我不知道Preferences
类在哪个包中。我怎样才能导入它?如果我使用自动填充功能,我可以使用import java.util.prefs.Preferences;
。但它不是机器人。它不包含getDefaultPreferences()
方法。请参阅以下链接中的代码。
在AddCookiesInterceptor.java
的第12行:
HashSet<String> preferences = (HashSet) Preferences
.getDefaultPreferences()
.getStringSet(Preferences.PREF_COOKIES, new HashSet<>());
http://tsuharesu.com/handling-cookies-with-okhttp/
/**
* This interceptor put all the Cookies in Preferences in the Request.
* Your implementation on how to get the Preferences MAY VARY.
* <p>
* Created by tsuharesu on 4/1/15.
*/
public class AddCookiesInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
HashSet<String> preferences = (HashSet) Preferences.getDefaultPreferences().getStringSet(Preferences.PREF_COOKIES, new HashSet<>());
for (String cookie : preferences) {
builder.addHeader("Cookie", cookie);
Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
}
return chain.proceed(builder.build());
}
}
答案 0 :(得分:3)
您需要创建一个PreferenceManager
类,其中包含mSharedPreferences
成员变量。通过调用mSharedPreferences
来实例化mApplicationContext.getSharedPreferences(name, mode)
。
答案 1 :(得分:1)
package com.trainerworkout.trainerworkout.network;
import android.content.Context;
import android.preference.PreferenceManager;
import android.util.Log;
import java.io.IOException;
import java.util.HashSet;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* This interceptor put all the Cookies in Preferences in the Request.
* Your implementation on how to get the Preferences MAY VARY.
*/
public class AddCookiesInterceptor implements Interceptor {
public static final String PREF_COOKIES = "PREF_COOKIES";
private Context context;
public AddCookiesInterceptor(Context context) {
this.context = context;
} // AddCookiesInterceptor()
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
HashSet<String> preferences = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet(PREF_COOKIES, new HashSet<String>());
for (String cookie : preferences) {
builder.addHeader("Cookie", cookie);
Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
} // for
return chain.proceed(builder.build());
} // intercept()
} // AddCookiesInterceptor
在某处你创建一个新的OkHttpClient并在你的所有请求中使用它。
public static OkHttpClient client = new OkHttpClient();
private OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new AddCookiesInterceptor(context));
builder.addInterceptor(new ReceivedCookiesInterceptor(context));
client = builder.build();