Android okhttp3自动保存cookie
废话不多说,上代码
public class RequestManager {
private OkHttpClient mOkHttpClient;
private static String BASE_URL = Constant.ServerletUrl;
private static RequestManager instance;
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
private Gson gson;
public RequestManager() {
mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(30000, TimeUnit.MILLISECONDS)
.readTimeout(30000, TimeUnit.MILLISECONDS)
.cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
cookieStore.put(httpUrl.host(), list);
}
@Override
public List<Cookie> loadForRequest(HttpUrl httpUrl) {
List<Cookie> cookies = cookieStore.get(httpUrl.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})
.build();
}
public static RequestManager getInstance() {
if (instance == null) {
synchronized (RequestManager.class) {
if (instance == null) {
instance = new RequestManager();
}
}
}
return instance;
}
/***
* post请求
*/
public void PostRequest(HashMap<String, Object> paramsMap, String url, final ResultCallback callback) throws UnsupportedEncodingException {
gson = new Gson();
String params = gson.toJson(paramsMap);
RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), params);
String requestUrl = BASE_URL + url;
final Request request = new Request.Builder()
.url(requestUrl)
.post(body)
.build();
Call callclient = mOkHttpClient.newCall(request);
callclient.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onError("网络请求失败,请稍后重试");
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (response.isSuccessful()) {
int code = response.code();
if (code == 200) {//请求成功
String result = response.body().string();
callback.onResponse(String.valueOf(code), result);
} else
callback.onError(response.message());
} else {
callback.onError("网络请求失败,请稍后重试");
}
}
});
}
public interface ResultCallback {
void onResponse(String code, String response);
void onError(String msg);
}
}