试图利用httpCache android?

我正在尝试使用okhttpclient进行改造以设置缓存…如何设置过期并将其添加到我的restApiManager?不确定是什么服务…

这是代码:

public class ApiManager {

    private static final String API_URL = "ip";


    public static AsynchronousApi getInstance() {
        if(service == null) {
            OkHttpClient okHttpClient = new OkHttpClient();
            File cacheDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
            HttpResponseCache cache = null;
            try {
                cache = new HttpResponseCache(cacheDir, 1024);
            } catch (IOException e) {
                e.printStackTrace();
            }
            okHttpClient.setResponseCache(cache);

            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint(API_URL)
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setClient(new OkClient(okHttpClient))
                    .setErrorHandler(new ErrorHandler() {

                        @Override
                        public Throwable handleError(RetrofitError arg0) {
                            if(arg0.getResponse().getStatus() == 404)
                                return new Exception("Url does not exists");

                            return new Exception(arg0.getMessage());
                        }
                    })
                    .build();
            service = restAdapter.create(AsynchronousApi.class);
        }

        return service;
    }



//    //create adapter
    private static final AsynchronousApi ASYNCHRONOUS_API = getInstance();

    //call service to initiate
    public static AsynchronousApi getAsyncApi() {
        return ASYNCHRONOUS_API;
    }

    //Call interface
    public interface AsynchronousApi {

        //USER

        //Register User
        @FormUrlEncoded
        @POST("/register")
        public void registerUser(
                @Field("email") String email,
                @Field("username") String username,
                @Field("password") String password,
                Callback<UserResponse> callback); //


         //Search User
        @GET("/search_user")
        public void searchUser(
                @Query("username") String username,
                Callback<UserResponse> callback); // userfound  cache users

解决方法:

您使用的是com.squareup.okhttp.OkHttpClient,但您应该使用以OkHttpClient作为参数的retrofit.client.OKClient.此外,如果okhttp jar已经在你的路径中,你根本不需要使用这个代码.只有在您遇到缓存可用性问题时才可能.

 private static RestAdapter REST_ADAPTER = new RestAdapter.Builder()
        .setEndpoint(API_URL)
        .setLogLevel(RestAdapter.LogLevel.FULL)
        .setClient(new OkClient(okHttpClient))
        .build();
上一篇:android-CompositeDisposable.clear导致OkHttp抛出java.lang.IllegalStateException:不平衡的输入/退出


下一篇:如何使用Retrofit 2.0获取原始响应和请求